1

フォームを使用してカテゴリをユーザーに追加しています。私のフォームには、利用可能なカテゴリに対応する多くのチェックボックスがあります。ユーザーはいつでも必要なカテゴリにチェックを入れたり外したりできます。

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

問題は、ユーザーがカテゴリのチェックを効果的に解除できないことです。理由はわかりますが、これを解決する最善の方法がわかりません。

助けてくれてありがとう :)

4

1 に答える 1

1

fields_for を使用すると、この場合の親友になる可能性があります

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

例: 私が取り組んでいるプロジェクトには食品があり、食品には多くの food_tag を含めることができます。これらのタグを管理するためのフォームは次のようになります。

= 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 で削除されます。

于 2013-03-27T19:39:32.900 に答える