Ransack, multiple column search, single field, rails 3

I am new to Ruby on Rails and I am building my first website. I have a user model with three columns: firstname , lastname and email . I use ransack to create a search engine, and I want to have one search field that will go through each column and display the result.

I did user_controller.rb as follows:

 @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 %> 

Providing me with 3 search fields, but I want only the one that goes through the first name, last name and email address.

Edit 1: After testing a few more, I found that the search field could not handle both the name and the name, or any spaces. I read that you can do helper_method as follows: Finding multiple fields with Ransack

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

But there is nothing about how to use it in a view. Why is it so difficult to just start, this is what you do: in Controller do it β†’ in the model do it β†’ in sight do it β†’ And don't forget to fix routes like this β†’

+7
source share
1 answer

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

The github page goes first: https://github.com/ernie/ransack

Look at the demo page Ransack is here: http://ransack-demo.herokuapp.com/ you should see that the first field does what you want (look in both lastname and firsname) and looking 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 of ​​the correct predicate , 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 this, you can do something similar in your view

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

which generates a "condition OR" query, as you can see on the demo page again (where the generated query is sent as a traditional SQL query)

Hope this helps

Greetings

+16
source

All Articles