I have written the following code to create a UI that enables filters to be added and removed from the query string:
<% @colours.each do 开发者_Go百科|colour| %>
<% if params[:colour].include?(colour) %>
<% # Already being filtered. Show remove link. %>
<% modified_params = params.dup %>
<% modified_params[:colour].delete_if {|v| v == colour } %>
<%= link_to "Remove #{colour}", modified_params %>
<% else %>
<% # Not being filtered. Show add link. %>
<%= link_to "Add #{colour}", params.merge('colour[]' => colour) %>
<% end %>
<% end %>
Clicking an 'Add' link adds the filter to the query string; clicking a 'Remove' link finds and removes the filter from the query string.
This works fine, but all looks rather messy to me. I am looking for suggestions to improve this code. Perhaps there is a better way to achieve this altogether, or maybe a gem that I have overlooked.
Any feedback much appreciated as I am relatively new to both Ruby and Rails.
Many thanks.
Update
Just to clarify, an example query string might be as follows:
?colour[]=Red&colour[]=Green&colour[]=Blue&size[]=Very+small&size[]=Small
Each filter link should continue to preserve other parameters that are present in the query string.
I would make a helper method, maybe "get_colour_link", and pass in your colours and params.
精彩评论