0

我的 RoR 项目中有以下模型:scope 和 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

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

我该如何解决?

4

2 回答 2

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)
于 2012-08-20T08:08:23.040 回答
1

尝试以下操作(我假设您设置attr_accessible正确):

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

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

于 2012-08-26T22:39:11.437 回答