0

I'm trying to change the option that is selected on collection_select on my form in rails.

My code look like this:

<%= f.collection_select :course_type_id, CourseType.where(:deleted => false), :id, :name, {}, {class: 'form-control  m-b', :selected => @course_template.course_type.name } %>

However the option selected always shows the first one and never changes unless the user selects a different option.

The resulting html looks like this:

<select class="form-control  m-b" selected="selected" name="course[course_type_id]" id="course_course_type_id">
    <option value="1">Driving</option>
    <option value="2">Pratical</option>
</select>

Any ideas on what I'm doing wrong?

InesM
  • 331
  • 4
  • 16

2 Answers2

3

It looks like you're putting the :selected key in the html_options argument attributes.

Here is the method definition for collection_select:

collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

Try this:

<%= f.collection_select :course_type_id, CourseType.where(:deleted => false), :id, :name, {:selected => @course_template.course_type.name}, {class: 'form-control  m-b' } %>
Ryenski
  • 9,582
  • 3
  • 43
  • 47
1

<%= f.collection_select :course_type_id, CourseType.where(:deleted => false), :id, :name, { :selected => @course_template.course_type.id }, {class: 'form-control m-b' } %>

  1. The selected parameter takes the value, and not the name of the option.
  2. From collection_select definition, selected option and html_options are different params.

For further understanding, refer here.

Community
  • 1
  • 1
Utsav Kesharwani
  • 1,715
  • 11
  • 25