【问题标题】:Problem with has_many :through and fields_forhas_many :through 和 fields_for 的问题
【发布时间】:2010-12-22 20:00:25
【问题描述】:

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

# 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

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

【问题讨论】:

    标签: ruby-on-rails ruby activerecord forms has-many-through


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 这不会改变任何事情 - 虽然很高兴知道,我根本不需要 for
      猜你喜欢
      • 2011-06-07
      • 2018-04-23
      • 2011-04-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-11
      • 1970-01-01
      • 2011-11-06
      • 2019-03-04
      相关资源
      最近更新 更多