alpaca
alpaca

Reputation: 1231

Rails: collection_check_boxes to filter search results

I'm trying to implement a search view which enables users to search other users based on keyword AND multiple checkboxes for their tags. I'm still trying to figure out how to place the collection_check_boxes right, so that view is rendered correctly. Here's what I have so far:

  <%= form_tag users_path, :method => 'get' do %>
    <%= collection_check_boxes :options, :tag_ids, Tag.order(:name), :id, :name, {multiple: true} %>
    <%= text_field_tag :search, params[:search], :placeholder => "Search", :id => "query" %>
    <%= submit_tag "Search", :name => nil, :style => "float:left;"%>
  <% end %>

Can you help me complete the view function above by making sure that, when a user clicks search collection_check_boxes will add something like tag=tag1&tag2&tag3 to the url?

Upvotes: 0

Views: 1088

Answers (1)

Mariusz Leśniewski
Mariusz Leśniewski

Reputation: 11

I will try :)

Generally everything is OK. Only small correction, if you change this line:

    <%= collection_check_boxes :options, :tag_ids, Tag.order(:name), :id, :name, {multiple: true} %>

to this:

    <%= collection_check_boxes :tag, :ids, Tag.order(:name), :id, :name, {multiple: true} %>

after submitting request, in URL will be something like this:

&tag%5Bids%5D%5B%5D=&tag%5Bids%5D%5B%5D=3&tag%5Bids%5D%5B%5D=2&search=test

more human view:

&tag[ids][]=&tag[ids][]=3&tag[ids][]=2&search=test

and this is OK. It always look like this when sending an array. In this particular case I've checked two checkboxes (with id=2 and 3). I don't know why there is also empty element :), but this is not a problem. I think there is no way to get results exactly like tag=tag1&tag2&tag3

In your "users" model you can get to the params by (after submitting form):

params[:tag][:ids] - array of id (checked checkboxes)
params[:search] - search input value

If you want to have checked some checkboxes on start (or after submit), add to collection_check_boxes additional parameter:

options = {:checked=>tag_ids}

and deliver in variable tag_ids array of checkboxes id (which should be checked). All the code looks like this:

<%if params.has_key?(:tag)%>
  <%tag_ids = params[:tag][:ids]%>
<%else%>
  <%tag_ids = Array.new%>
<%end%>

<%=form_tag drons_path, :method => 'get' do %>
  <%=collection_check_boxes :tag, :ids, Tag.order(:name), :id, :name, {multiple: true}, options = {:checked=>tag_ids}%>
  <%=text_field_tag :search, params[:search], :placeholder => "Search", :id => "query"%>
  <%=submit_tag "Search", :name => nil, :style => "float:left;"%>
<%end %>

Upvotes: 1

Related Questions