Jonathan Roy
Jonathan Roy

Reputation: 903

Ruby on Rails: Issue with has_many association and form checkboxes

I am using a form to add categories to a user. In my form I have many checkboxes that correspond to available categories. A user can check and uncheck the categories he wants at anytime.

class User < ActiveRecord::Base
  has_many :categories, :through => :classifications
end

class Category < ActiveRecord::Base
  has_many :users, :through => :classifications
end

class Classification < ActiveRecord::Base
  belongs_to :user
  belongs_to :category
end

= form_for @user
  - @all_categories.each do |category|
    %label
      = check_box_tag "user[category_ids][]", category.id, @user.categories.include?(category)
      = category.name

The problem is that the user cannot effectively uncheck a category. I understand why but I don't know the best way to solve this.

Thanks for the help :)

Upvotes: 1

Views: 718

Answers (1)

Bob McCown
Bob McCown

Reputation: 127

Using fields_for might be your best friend for this one

http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for

Example: A project Im working on has foods, and foods can have many food_tags. The form for managing these tags looks like this:

= food_form.fields_for "tags" do |tags_form|
  - Tag.all.each_with_index do |tag, index|
    = fields_for "#{type.downcase}[food_tags_attributes][#{index}]", food.food_tags.find_or_initialize_by_tag_id(tag.id) do |tag_form|
      = tag_form.hidden_field :id
      = tag_form.hidden_field :tag_id
      = tag_form.check_box :_destroy, {:checked => tag_form.object.new_record? ? false: true}, "0", "1"
      = tag_form.label :_destroy, tag.display_name + " #{}"

Note I'm using the _destroy attribute inverted. So, if the box is checked, it'll add, if its unchecked, it'll remove it on food.update_attributes.

Upvotes: 1

Related Questions