2013-03-27 75 views
1

我正在使用表单向用户添加类别。在我的表单中,我有很多对应于可用类别的复选框。用户可以随时检查并取消选中他想要的类别。Ruby on Rails:发布has_many关联和表单复选框

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 

问题是用户无法有效地取消选中某个类别。我明白为什么,但我不知道解决这个问题的最佳方法。

感谢您的帮助:)

回答

1

使用fields_for可能是你最好的朋友为这一个

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

例:某项目进出口工作的有食品,食品和可以有很多food_tags。管理这些标签的形式如下所示:

= 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 + " #{}" 

注意我正在使用_destroy属性倒置。所以,如果该框被选中,它会添加,如果未选中,它将在food.update_attributes上删除它。

+0

你能提供一个例子吗?我从来没有使用fields_for这种方式。 – 2013-03-27 19:51:07

+0

新增示例 – 2013-03-28 12:52:01

+0

感谢您的帮助! – 2013-03-29 19:31:54

相关问题