Search by name with Ransack

I have a Ransack form in a legacy project that looks like this:

<%- ransack_form_options ||= {} -%>
<%- search_field_options ||= {} -%>
<%- search_field_options.merge! autocomplete: "off", id: "q" -%>

<div class="search-form">
  <%= search_form_for(@q, ransack_form_options) do |f| %>
    <%= f.text_field search_on, search_field_options %>
    <%= f.submit 'Search' %>
    <%= button_tag '', class: 'cancel-search' %>
  <% end %>
</div>

      

The value search_on

is student_first_name_or_student_last_name_or_student_email_cont

.

This works for searches by name or by name or by email. But what if I want to find the full name or first name, last name, or email address? How can i do this?

+2


source to share


2 answers


What you want is something like:

  ransacker :full_name do |parent|
    Arel::Nodes::InfixOperation.new(
      '||',
      Arel::Nodes::InfixOperation.new(
        '||',
        parent.table[:first_name], Arel::Nodes.build_quoted(' ')
      ),
      parent.table[:last_name]
    )
  end

      



This will be used in your model, and then you can write the full_name_or_first_name_or_last_name or whatever you want to write. I realize this is 3 years later, but hopefully it might be helpful for someone else.

0


source


Full name search with Ransack (first and last name)



ransacker :full_name do |parent|
  Arel::Nodes::NamedFunction.new('CONCAT_WS', [
     Arel::Nodes.build_quoted(' '), parent.table[:first_name], parent.table[:last_name]
  ])   
end

      

0


source







All Articles