has_many :through 和 fields_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
订阅还有一个布尔列“通知”,我需要单独配置它,所以我研究了 应用程序编程接口, ,按照示例并为我的表单编写了以下代码:
- 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