用Ransack全名搜索

时间:2015-07-21 22:32:41

标签: ruby-on-rails ransack

我在继承的项目上有一个Ransack表单,如下所示:

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

search_on的值为student_first_name_or_student_last_name_or_student_email_cont

这适用于使用名字或姓氏或电子邮件进行搜索。但是如果我想搜索全名或名字或姓氏或电子邮件怎么办?我怎么能这样做?

3 个答案:

答案 0 :(得分:1)

搜索带有搜索结果的全名(名字和姓氏)

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

答案 1 :(得分:1)

今天可以更轻松地完成:

ransacker :full_name do
  Arel.sql("CONCAT_WS(' ', users.first_name, users.last_name)")
end

何时有连接表:

ransacker :user_name_with_contry_code do
  Arel.sql("CONCAT_WS(' | ', countries.code, users.first_name)")
end

https://github.com/activerecord-hackery/ransack/wiki/Using-Ransackers

答案 2 :(得分:0)

您想要的东西是这样的:

  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

这将出现在您的模型中,然后在您的视图中,您可以编写full_name_or_first_name_or_last_name或您想要编写的任何内容。我意识到这已经晚了3年了,但是希望对其他人有帮助。

相关问题