Search code examples
ruby-on-railsransack

Searching multiple fields with Ransack


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.


Solution

  • 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.