0

我的RoR項目中有以下模型: scope和project_scopes。Rails habtm nested select編輯時沒有選擇正確的值

項目has_many :scopes, through: :project_scopes。還項目accepts_nested_attributes_for :project_scopes

我幾個選擇添加範圍的項目:

項目/ _form.html.haml

= form_for(@project) do |f| 
    = f.fields_for :project_scopes do |builder| 
    = render 'project_scope_fields', f: builder 
    = link_to_add_fields 'Add scopes', f, :project_scopes 

項目/ project_scope_fields.html.haml

= f.select :scope_id, options_from_collection_for_select(@scopes, "id", "name"), {include_blank: true, class: "project_scopes"} 
= f.hidden_field :_destroy 

這成功創建所有範圍的項目。當我點擊編輯時,它呈現相同的形式並顯示所有範圍選擇,但它們沒有正確的選定值。

我該如何解決這個問題?

回答

4

查看options_from_collection_for_select的文檔:它需要4個參數,最後一個是所選的選項。你沒有提供。試試這個:

= f.select :scope_id, options_from_collection_for_select(@scopes, "id", "name", @project.scope) 

或者乾脆使用collection_select幫手:

= f.collection_select(:scope_id, @scopes, :id, :name) 
1

嘗試以下(和我假設,你正確設置attr_accessible):

= f.select :scope_id, @scopes.map{|s| [s.name, s.id]}, {include_blank: true, class: "project_scopes"} 

順便說一句 - Scope可能不是最好的型號名稱。