Home > Software engineering >  Rails: Using selected => when setting a default value for my collection_select drop down on a for
Rails: Using selected => when setting a default value for my collection_select drop down on a for

Time:05-05

I'm stumped on this one.. I'm using this:

<%= f.collection_select :project_type, @project_types, :name, :name, {:selected => "Other"}, class: 'form-control selectpicker', data: { 'live-search' => 'true' } %>

to set the project type to default when the user creates a new item. But when I edit the item it defaults back to whatever :selected => is set to.

My question is if there is some type of conditional I can add in "edit" or "create" that doesn't change my data when I'm editing. OR is there a different way to set a default value that has a different behavior than :selected =>

CodePudding user response:

The best way in my opinion would be to set the default value on the object itself and remove the selected option from the collection_select, so on the controller action where you create the new object you can set it:

Model.new(project_type: 'other')

You can also set the default value in the database itself which should work hopefully or use some ActiveRecord method to do that:

Rails: How can I set default values in ActiveRecord?

Or the other option would be to set it on the collection_select like this:

<%= f.collection_select :project_type, @project_types, :name, :name, { selected: (f.object.project_type || "Other") }, class: 'form-control selectpicker', data: { 'live-search' => 'true' } %>

Replace f.object with the instance variable you might already have.

  • Related