I'm trying to get the ActionView-Helper collection_select
to take a value that will be preselected in the dropdown-menu.
Neither (:selected
in the html-option-hash)
<%= collection_select(:my_object, :my_method, @my_collection, :id, :description_string, {}, {:selected => @my_collection_object.id}) %>
nor (:selected
in the option-hash)
<%= collection_select(:my_object, :my_method, @my_collection, :id, :description_string, {:selected => @my_collection_object.id}, {}) %>
seem to work.
What am I doing wrong? Can anyone help me on this one?
From the docs:
Sample usage (selecting the associated Author
for an instance of Post
, @post
):
collection_select(:post, :author_id, Author.all, :id, :name_with_initial)
If @post.author_id
is already 1, this would return:
<select name="post[author_id]">
<option value="">Please select</option>
<option value="1" selected="selected">D. Heinemeier Hansson</option>
<option value="2">D. Thomas</option>
<option value="3">M. Clark</option>
</select>
So you just need to make sure that @my_object.my_method
returns a value that matches one of the available option values. If there's a match then that option will be selected.
According to the docs, if @my_object.my_method
has the same value as one of the options, that one will be selected by default.
Conversely, you could try using options_from_collection_for_select
in conjunction with select_tag
:
<%= select_tag 'my_object[my_method]', options_from_collection_for_select(@my_collection, :id, :description_string, @my_collection_object.id) %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With