has_many :through と field_for の問題
-
12-09-2019 - |
質問
私にはかなり基本的な関連性があります。
# user.rb
class User < ActiveRecord::Base
has_many :services, :through => :subscriptions
has_many :subscriptions, :accessible => true
accepts_nested_attributes_for :subscriptions
end
# service.rb
class Service < ActiveRecord::Base
has_many :users, :through => :subscriptions
has_many :subscriptions
end
# subscription.rb
class Subscription < ActiveRecord::Base
belongs_to :user
belongs_to :service
end
サブスクリプションには、個別に設定する必要があるブール値の列「通知」もあります。そのため、 API, 、例に従って、私のフォーム用にこのコードを思いつきました。
- if current_user.subscriptions.length > 0
%fieldset#subscriptions
%legend Abonnements
%table
%tr
%th.name
%th.notification Notifications?
- for subscription in current_user.subscriptions do
%tr
- f.fields_for :subscriptions, subscription do |s|
%td=subscription.service.name
%td= s.check_box :notification
しかし、フォームを保存すると、関連付けられているすべてのサブスクリプションが破棄されます。チェックボックスをオンにしても削除されませんが、 しかし、チェックボックスも保存されません. 。誰か私が間違っていることを知っていますか?
解決
2時間近く試した結果、ようやく動作するようになりました。コードを少し変更するだけで十分です。
# _form.html.haml
# […]
- if current_user.subscriptions.length > 0
%fieldset#subscriptions
%legend Abonnements
%table
%tr
%th.name
%th.notification Notifications?
- f.fields_for :subscriptions do |sub|
%tr
%td= sub.object.service.name
%td
= sub.check_box :notification
= hidden_field_tag "user[service_ids][]", sub.object.service.id
# […]
なぜなら params[:user][:service_ids]
が空だった場合、関連付け全体が削除されました。
他のヒント
フォームを使用してサブスクリプションを送信していません。チェックボックスをクリックしないと、そのサブスクリプションに対して送信するものが何もないため、サブスクリプションはネストされた属性機能によって消去されます。サブスクリプションのサービス ID を隠しフィールドに入力してみてください。
ネストされた属性のフォームの設定も間違っていると思います。これを試して:
- if current_user.subscriptions.length > 0
%fieldset#subscriptions
%legend Abonnements
%table
%tr
%th.name
%th.notification Notifications?
- f.fields_for :subscriptions do |sub|
%tr
%td= sub.object.service.name
%td
= sub.check_box :notification
= sub.hidden_field :service_id
所属していません StackOverflow