2009-12-03 60 views
2

我有一个非常基本的关联关系:问题用的has_many:通过和fields_for

# 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

试图围绕近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]是空的,它删除整个关联。

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 
+0

这并没有改变任何东西 - 虽然很高兴知道,我根本不需要“for”。 – 2009-12-03 14:16:25