2

我有一个非常基本的关联:

# 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

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

4

2 回答 2

2

在尝试了将近 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]是空的,所以删除了整个关联。

于 2009-12-03T15:30:04.680 回答
0

您没有使用表单提交任何订阅。如果不单击该复选框,您将无法为该订阅提交任何内容,因此这些订阅将被嵌套属性功能清除。尝试使用订阅的服务 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
于 2009-12-03T13:55:07.843 回答