我有一个非常基本的联想:
# 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
订阅还有一个 bool 列“通知”,我需要单独配置它,所以我查看了 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]
是空的,它删除了整个关联。
关于ruby-on-rails - has_many :through and fields_for 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1839925/