我的RoR项目中有以下模型: 范围和project_scopes。
项目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
这可以成功创建包含所有范围的项目。当我单击编辑时,它会呈现相同的表单并显示所有范围选择,但它们没有正确的选定值。
我该如何解决这个问题?
答案 0 :(得分: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 :(得分:1)
尝试以下(我假设您正确设置attr_accessible
):
= f.select :scope_id, @scopes.map{|s| [s.name, s.id]}, {include_blank: true, class: "project_scopes"}
顺便说一下 - Scope
可能不是最佳型号名称。