module CoursesHelper
def selected_option(hash, key)
unless hash.blank?
hash[key]
else
""
end
end
end
select(:search, :course_category_id, [[_("Všechny kategorie"), ""]]+@course_categories.collect {|d| [ d.title, d.id ] },
:selected => selected_option(params[:search], :course_category_id) )
Refactorings
No refactoring yet !
Adam
October 15, 2008, October 15, 2008 13:41, permalink
I'm guessing you probably don't want to use the form builder at all here. But since I do not know enough about your project, I'll just suggest this:
def search @search = OpenStruct.new(params[:search]) end
<% fields_for :search do |s| %>
<%= s.select :course_category_id, [[_("Všechny kategorie"), ""]] +
@course_categories.map { |category| [ category.title, category.id ] } %>
<% end %>
nakajima
October 16, 2008, October 16, 2008 00:25, permalink
I like Adam's idea of using fields_for. I'd go a step further and pull the options into a helper method as well (I don't like seeing #collect inside an erb tag). Also, I'm not quite sure why there's a need for an OpenStruct there.
For the selected_option method you pasted, I thought a more meaningful name would be worthwhile, so I renamed it to current_category. The implementation I added is pretty simple, albeit crude. It definitely makes assumptions about your params that may or may not be a good idea, but I'll leave that up to you.
module CoursesHelper
def category_options
[[_("Všechny kategorie"), ""]] + @course_categories.collect {|d| [ d.title, d.id ] }
end
def current_category
params[:search][:course_category_id] rescue nil
end
end
select(:search, :course_category_id, category_options, :selected => current_category)
Adam
October 16, 2008, October 16, 2008 02:30, permalink
@nakajima - "Also, I'm not quite sure why there's a need for an OpenStruct there."
To store the values of the submitted form. It could be an ActiveRecord object or any kind of object that exposes the necessary methods, but OpenStruct was all I needed for demonstration purposes. It negates the need to set :selected => ..., which is rather ugly and not how FormBuilder should be used. But, like I said, I'm not sure FormBuilder is appropriate here anyway.
How would you made this simplier? I mean especially the :selected option