(NOTE: I have read http://shiningthrough.co.uk/Select-helper-methods-in-Ruby-on-Rails, but still don’t know what to pick)
I have a form that will be used as a search filter (The method is get).
<%= form_tag(reports_courses_allocated_path, :method =>'get') %>
<%= collection_select(:course, :id, @courses, :id, :title, :include_blank => "All Courses") %>
</form>
The above produces the output I want for the tags, but there is no “selected” parameter where I could pass in a params value. I also don’t like the fact that the name is course[id], I would rather have it named course_id
I could do:
<%= select_tag(:course_id, raw("<option>All Courses</option>") + options_from_collection_for_select(@courses, :id, :title, params[:course_id])) %>
But I don’t like the fact that I am concatenating options, but that might be my best bet.
Any opinions/suggestions?
Must it be a params value that sets ‘selected’ in your case? The ‘selected’ value for collection_select is based on the value of @course.id — you could make sure that @course represents the one that should be selected.
As for the name, I would stick with the Rails default even when writing your own HTML. It’s what dictates how the parameters come into your action. If your elements have names course[id], course[name], course[type], etc., the params would be
which is convenient because then you can call
Also, you do not need to close your forms with your own HTML form tag. The method form_tag takes a block:
And finally… I’ve used select_tag and built up an options list before. It can get ugly but you could build it in methods in the view helper where it doesn’t clutter up your rhtml and where it can be unit tested.