Searching multiple fields with Ransack

强颜欢笑 提交于 2020-01-02 10:58:19

问题


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.


回答1:


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.




回答2:


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




回答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 %>


来源:https://stackoverflow.com/questions/13309062/searching-multiple-fields-with-ransack

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