I have a page where I need to send parameters so that the url looks like this:
/my_controller?stores%5BStoreName%5D=1
However, when I try to form my link_to I get this url:
/my_controller?stores%5B%5D=5BStoreName&stores%5B%5D=1
This is the link_to code from my view:
<%= link_to store, my_controller_path(:stores => [store, 1]) %>
How do I change my code so that I get the url structured with the params that match the link that I need?
My params should look like {"stores"=>{"StoreName"=>"1"} , but right now they look like {"stores"=>["StoreName", "1"].
Controller:
Here is the index method within my controller that is reading this hash – for clarity.
def index
@all_stores = Product.all_stores
@selected_stores = params[:stores] || session[:stores] || {}
if @selected_stores == {}
@selected_stores = Hash[@all_stores.map {|store| [store, store]}]
end
if params[:stores] != session[:stores]
session[:stores] = params[:stores]
redirect_to :stores => @selected_stores and return
end
@products = Product.order("created_at desc").limit(150).find_all_by_store(@selected_stores.keys).group_by { |product| product.created_at.to_date}
. . . etc
Background:
The bigger picture here is that the destination page (that the above link will link to) is a page that lists all products filtered by store. The way the filter normally works is with a set of checkboxes (the user can mark checkboxes to show products from specific stores). The desired link will take users directly to this page with the desired filter already applied – without having to mark checkboxes.
For additional reference, here is that checkbox helper that filters that destination page’s products:
<%= check_box_tag "stores[#{store}]", 1, @selected_stores.include?(store), :id => "stores_#{store}" %>
Use
<%= link_to store, my_controller_path(:stores => { store => 1}) %>