2009-12-03 57 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