Searching multiple fields with Ransack
Asked Answered
B

3

3

I'm using Ransack to allow advanced searching on my users. Currently, the users have first_name, middle_name, and last_name columns. Here is my code:

.field
  = f.attribute_fields do |a|
    = a.attribute_select
    ...

How can I have a custom one called 'Name', that lets the user search through all three of the columns mentioned above?

Note I would still like to keep the remaining attributes as options as well, such as email, phone number, etc. Please keep this in mind when determining an answer.

Bygone answered 9/11, 2012 at 13:32 Comment(0)
E
3

I would suggest to provide a dedicated column for this search. While that might create redundant data, it is way easier to search than doing some SQL magic on the existing columns.

You can easily automate the setting of this field:

before_save :set_full_name

def set_full_name
  self.full_name = [first_name, middle_name, last_name].reject(&:blank?).join(" ")
end

Then you can use the normal ransack methods to search this field.

Eme answered 9/11, 2012 at 15:45 Comment(1)
Yeah, that is a great idea. Thanks @Thilo.Bygone
I
3

Another approach is to search every attribute of the model, excluding only the fields that you don't want to search. To do this, you could create a custom helper method that builds the label and search field name expected by Ransack's search method. The following method (located in a helper) returns a concatenation of all attributes that you wish to search in a way that Ransack expects:

def most_attributes_cont
  most_attributes = []
  attributes_to_exclude = [
    "id",
    "created_at",
    "updated_at"
  ]
  ModelName.column_names.each do |column_name|
    most_attributes << column_name unless column_name.in?(attributes_to_exclude)
  end
  most_attributes.join("_or_") + "_cont"
end

Then, just add the method call to your search form:

<%= search_form_for @q do |f| %>
  <%= f.label most_attributes_cont %>
  <%= f.search_field most_attributes_cont %>
  <%= f.submit %>
<% end %>
Indian answered 11/8, 2014 at 6:19 Comment(0)
M
3

Use this to search multiple fields:

= f.text_field(: first_name_or_middle_name_or_last_name_cont)

This will generate a query like this:

where first_name like '%q%' or middle_name like '%q%' or last_name like'%q%' 

when you fill in a q as search parameter

Metallist answered 8/10, 2015 at 20:8 Comment(1)
This "works" but produces entirely non-intuitive behavior in this situation. As a user, one would expect that typing in "first_name last_name" will yield the corresponding user. That does not work using this method as ransack will try to search first_name for "first_name last_name."Hostile

© 2022 - 2024 — McMap. All rights reserved.