2014-04-28 41 views
0

我有兩個模型通過連接表連接:用戶和代理(由AgencyUserRelationships加入)。用戶有很多關係,每個關係都有一個代理,但他們不一定與所有代理有關係。SimpleForm檢查現有的has_many記錄

我想爲用戶創建一個Simpleform,它將所有代理顯示爲複選框列表,其中現有關係已被檢查。提交表單更新/刪除現有的關係,如果他們沒有選中,並創建新的,如果他們被檢查。這聽起來像一個工作,accepts_nested_attributes_for但我的嘗試是失敗(見下文)

User.rb

has_many :agency_user_relationships 
accepts_nested_attributes_for: agency_user_relationships 

AgencyUserRelationship.rb

belongs_to :user 
belongs_to :agency 

簡單的表單代碼

= simple_form_for user do |f| 
    = f.input :agency_user_relationships, collection: Agency.all, as: :check_boxes, label: t(:agencies) 
    = button_tag type: :submit, "Add" 

這最終給了我一個表格,每個機構都有一行(這是我的意思噸),但現有的關係不檢查。

我看着Simpleforms docs,但後面的例子只是給了我一個兩行的窗體來編輯嵌套的資源,這不是我真正想要的,我不這麼認爲。

回答

0

原來我非常接近。我將f.input改爲f.association,Rails知道該怎麼做。

原來我simpleform代碼到

= simple_form_for user do |f| 
    = f.association :agency_user_relationships, as: :check_boxes, collection: Agency.all, label: t(:agencies) 
    = button_tag type: :submit, class: 'btn btn-primary controls' do 
    = t(:add_agency) 

現在的形式表明了存在的所有機構,但已經有我的用戶關係的那些被默認選中。其餘的是控制器代碼。