Searching by full name with Ransack

烂漫一生 提交于 2020-01-02 10:19:46

问题


I have a Ransack form on a project I inherited 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 of search_on is student_first_name_or_student_last_name_or_student_email_cont.

This works for searching by first name or by last name or by email. But what if I want to search for full name or first name or last name or email? How can I do that?


回答1:


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

That will go in your model, and then in your view you can write full_name_or_first_name_or_last_name or whatever you wanted to write. I realize this is 3 years late, but hopefully this can be helpful to someone else.




回答2:


Searching full_name with ransack (first_name & 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


来源:https://stackoverflow.com/questions/31550779/searching-by-full-name-with-ransack

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