在我继承的一个项目中,我有一个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。
这适用于通过名字、姓氏或电子邮件进行搜索。但是,如果我想搜索全名、名、姓或电子邮件怎么办?我怎么能这么做?
发布于 2019-06-18 12:20:37
用ransack搜索full_name (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发布于 2019-01-01 16:51:17
你想要的是:
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年,但希望这能对其他人有所帮助。
发布于 2021-04-23 10:01:00
今天,可以更容易地做到:
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)")
endhttps://github.com/activerecord-hackery/ransack/wiki/Using-Ransackers
https://stackoverflow.com/questions/31550779
复制相似问题