Ransack, search multiple columns, one field, rails 3

Remi Champ picture Remi Champ · Mar 14, 2013 · Viewed 13.9k times · Source

I'm new to Ruby on Rails, and I'm creating my first site. I have a user model with 3 columns: firstname, lastname and email. Im using ransack to make a search engine, and i want to have one search field that will go through every column and display the result.

I have made a user_controller.rb looking like this:

@q = User.search(params[:q])
@users = @q.result(:distinct => true)

And my User\index.html.erb looks like this:

<%= search_form_for @search do |f| %>
  <div class="field">
    <%= f.label :firstname_cont , "Firstname" %>
    <%= f.text_field :firstname_cont %>
    <%= f.label :lastname_cont , "Lastname" %>
    <%= f.text_field :lastname_cont %>
    <%= f.label :email_cont , "Email" %>
    <%= f.text_field :email_cont %>
  </div>
  <div class="actions"><%= f.submit "Search" %></div>
<% end %>

Giving me 3 search fields, but i only want one that goes through firstname, lastname and email.

Edit 1 : After testing some more, I found out that the search field can't handle both firstname AND lastname, or any whitespaces. I have read that it is possible to make a helper_method like this: Searching multiple fields with Ransack

And when I get the search result I get thrown into my model index etc: user / index. Where can I change this?

But there is nothing on how to use it in the view. Why is it so hard to just whrigt, this is what you do :in Controller do this -> in model do this -> in view do this -> And dont forget to fixs the routes like this ->

Answer

phron picture phron · Mar 16, 2013

First of all, before asking try to search a bit through the gem docs and googling a bit ^_^.

The first one to refer is the github page : https://github.com/ernie/ransack

Looking at the demo page of Ransack here : http://ransack-demo.herokuapp.com/ you should see the first field does what you want (search in both in lastname and firsname) and having a look at the source code of the page you should see this line

<input id="q_first_name_or_last_name_cont" name="q[first_name_or_last_name_cont]" size="30" type="text" />

which gives you an idea on the correct predicate to use, you can also have a list of them here : https://github.com/ernie/ransack/blob/master/lib/ransack/constants.rb (always in the gem doc on github).

Based on that you can do something like that in your view

<%= f.text_field :lastname_or_first_name_or_email_cont, :placeholder => 'full name or email contains' %>

that generates a 'OR condition' query, as you can see in the demo page again (where the query generated is dispayed as a traditional SQL query)

Hope this helps

Cheers