2013-03-27 93 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