我有一个很基本的联系:

# 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

订阅还有一个布尔列“notification”,我需要单独配置它,因此我查看了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

但当我保存表单时,所有关联的订阅都会被销毁。然而,当我选中复选框时,它不会被删除,但复选框也不会被保存。有人知道我做错了什么吗?

最佳答案

经过两个小时的努力,我终于成功了。稍微修改一下代码就足够了:

# _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]是空的,所以它删除了整个关联。

10-07 12:25