Rails habtm nested select编辑时没有选择正确的值

问题描述:

我的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 

这成功创建所有范围的项目。当我点击编辑时,它呈现相同的形式并显示所有范围选择,但它们没有正确的选定值。

我该如何解决这个问题?

查看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) 

尝试以下(和我假设,你正确设置attr_accessible):

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

顺便说一句 - Scope可能不是最好的型号名称。