简体   繁体   English

Ruby on Rails:has_many关联和表单复选框出现问题

[英]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 :) 谢谢您的帮助 :)

Using fields_for might be your best friend for this one 使用fields_for可能是您最好的朋友

http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for 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. 示例:我正在从事的项目中有食物,而食物可以有许多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. 注意我正在使用_destroy属性倒置。 So, if the box is checked, it'll add, if its unchecked, it'll remove it on food.update_attributes. 因此,如果选中该框,则将添加;如果未选中,则将其删除在food.update_attributes上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM