I have a drop down list of Type in my Products model. I want to be able to search in the Products index.html.erb so a user selects a type from a drop down list, clicks search and all the products matching that type are returned. I can get normal search methods working where the user enters in their search in a text box but I cannot get it working when they just select from a dropdown. Can anyone help?
A:
In your controller :
def index
@products = Product.all :conditons => {:type => params[:type]}
end
In your view:
<% form_tag products_path, :method => :get do %>
<%=select_tag :type, options_for_select(Product::TYPES.map{ |type| [type, type]}), :onchange => "this.form.submit();" %>
<%=submit_tag "Search" %>
<% end %>
NB: The options_for_select accepts an array of pairs as [label, value], so we use map to build it.
Jakub Hampl
2010-05-11 16:18:46
I store Type in Product as a String.In the Product model I set the options for Type with TYPES = ["type1", "type2"]
2010-05-11 16:27:37
And the code I posted doesn't work? Does it give you an error?
Jakub Hampl
2010-05-11 16:29:42
My issue is I can't get it to actually search as I don't know how to with a dropdown, this is what I have in the index.html.erb find type <%= select("product", "type", Product::TYPES)%> <%= submit_tag "Search", :name => "submit_search", :class => "button" %>
2010-05-11 16:35:47
OK, I added some code that should help you in the view.
Jakub Hampl
2010-05-11 16:47:52
Still having trouble on that, get an error undefined method `TYPES' for #<Class:0x72a1f50>. <%=select_tag :type, options_for_select(Product.TYPES.map{ |type| [type, type]})
2010-05-11 17:01:17
Mayby then `Product::TYPES` would help? This really depends on your code - you need to get the values for the select from somewhere - the best place is your model where they are already defined.
Jakub Hampl
2010-05-11 17:58:53