0

I have the following models in my RoR project: scope and project_scopes.

Project has_many :scopes, through: :project_scopes. Also project accepts_nested_attributes_for :project_scopes.

I add scopes to projects by several selects:

projects/_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

projects/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

This successfully creates projects with all scopes. When I click edit, it renders same form and displays all scope selects, but they do not have the correct selected value.

How do I fix this?

Michael
  • 548
  • 8
  • 30

2 Answers2

4

Look at the documentation for options_from_collection_for_select: It takes 4 parameters, the last one being the selected option. You're not supplying that. Try this:

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

or simply use the collection_select helper:

= f.collection_select(:scope_id, @scopes, :id, :name)
Thilo
  • 17,565
  • 5
  • 68
  • 84
1

Try following (and I'm assuming, you're setting attr_accessible correctly):

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

Btw - Scope may not be best model name.