代码之家  ›  专栏  ›  技术社区  ›  nocksock

问题有很多:通过和字段

  •  2
  • nocksock  · 技术社区  · 15 年前

    我有一个很基本的联系:

    # 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
    

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

    2 回复  |  直到 15 年前
        1
  •  2
  •   nocksock    15 年前

    经过近两个小时的尝试,我终于让它工作起来了。只要稍微修改一下代码就足够了:

    # _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
  •  0
  •   Clinton Dreisbach    15 年前

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