Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails collection_select default option?

so I'm putting together a collection select.

<%= collection_select :PriceRange, "7", PriceRange.where('value > 0'), :value, :name %> 

I'm trying to get the default selection to be PriceRange with the id of 7, this is independent and doesn't rely on any of the users settings, its part of a form that changes the items displayed on the page by their price range.

* * * UPDATED EFFORTS * * * 

I added

@price_higher = PriceRange.find(7) 

to the Controller that handles the view, and added

, {:selected => @price_higher.value} 

inside the collection_select. It seems to do the trick, although was looking for a less complicated way of doing it all inside the collection_select.

like image 969
mediarts Avatar asked Jun 24 '12 04:06

mediarts


2 Answers

Add the :selected option.

Example:

collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:selected => "whatever_value"}) 

Example took from: ApiDock

In your case:

<%= collection_select :PriceRange, "7", PriceRange.where('value > 0'), :value, :name, {:selected => "whatever"} %> 
like image 160
Nobita Avatar answered Sep 18 '22 14:09

Nobita


If you want to select a default value from data base then use,

collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:selected => @authors.first}) 

If you want to prompt a message then use,

collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:prompt => "Select Post"}) 
like image 29
honey Avatar answered Sep 19 '22 14:09

honey