Searching multiple fields with Ransack

自古美人都是妖i 提交于 2019-12-06 08:53:41
Thilo

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.

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

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 %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!