mercredi 1 juin 2016

Rails check_box_tag keep checked state (if checked) after page load

I'm following this guide for multi-checkbox in rails. I am using Rails 3 conventions, so I still have attr_accessible instead of strong parameters. Everything seems to work fine except I get this error:

undefined method `match' for []:Array

userprofile.rb model:

class Userprofile < ActiveRecord::Base

  before_save do
    self.expertise.gsub!(/[\[\]\"]/, "") if attribute_present?("interest")
  end

  attr_accessible :interest, :user_id, :country, :state_prov, :city
  serialize :interest, Array

userprofiles_helper.rb:

module UserprofilesHelper
  def checked(area)
      @userprofile.interest.nil? ? false :      @userprofile.interest.match(area)
  end
end

_form.html.erb:

<h3>Area of Interest</h3>

  <%= label_tag 'interest_physics', 'Physics' %>
  <%= check_box_tag 'userprofile[interest][]', 'Physics', checked("Physics"), id: 'interest_physics' %>

  <%= label_tag 'expertise_maths', 'Maths' %>
  <%= check_box_tag 'userprofile[interest][]', 'Maths', checked("Maths"), id: 'interest_maths' %>

If I remove the checked helper method, then the checkbox value does not persist. I've been trying to fix the undefined method 'match' error. Or find an alternate way to keep the correct checkbox value checked when I edit the form.

Any suggestions would help, thank you!

Aucun commentaire:

Enregistrer un commentaire