使用全名搜索时,Gem Ransack 不会返回任何结果 [英] Gem Ransack doesn't return any results when searched with full name

查看:47
本文介绍了使用全名搜索时,Gem Ransack 不会返回任何结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rails 3 中使用 Ransack.

I'm using Ransack with Rails 3.

我的观点:

  <%= search_form_for @search do |f| %>
    <%= f.text_field :first_name_or_last_name_or_company_cont, :style => 'width:150px;padding-top:6px;' %><p class="button">
    <%= f.submit "Search by name or company" %></p>
  <% end %>

我的架构:

create_table "users", :force => true do |t|
    t.string   "first_name",                  
    t.string   "last_name"

在我拥有的用户模型上:

on the User model I have:

  def full_name
    "#{self.first_name} #{self.last_name}"
  end

在控制台上工作.

如果我有具有 first_name = "Foo", last_name = "Bar" 的用户,当我搜索任何一个时,我都会得到预期的结果.

If I have user with first_name = "Foo", last_name = "Bar" , when I search with either one, I get the results as expected.

当我使用 full_name = "Foo Bar" 搜索时,我没有得到任何结果.

When I search with full_name = "Foo Bar", I get no results.

我尝试将 Ransack 的 text_field 更改为:

I tried changing my text_field for Ransack to:

<%= f.text_field :first_name_or_last_name_or_company_or_full_name_cont

我得到 first_name_or_last_name_or_company_or_full_name_cont 未定义

有没有一种快速的方法来解决这个问题,而无需在我的用户表上为 full_name 添加另一列?

is there a quick way to solve this without adding another column for full_name on my users table?

还有:

     7: def index
     8:   search_params = params[:q]
 =>  9:   binding.pry

[1] pry(#<UsersController>)> search_params
=> {"first_name_or_last_name_or_company_cont"=>"Foo Bar"}

我想我可以在这里拆分键值来仅搜索名字.

I guess I can split key value here to search the first name only.

推荐答案

您必须使用 Ransacker.将此添加到您的 User 模型中:

You have to use a Ransacker. Add this in your User model:

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

您可以查看Ransack GitHub wiki 以获取更多示例.

You can check the Ransack GitHub wiki to more examples.

这篇关于使用全名搜索时,Gem Ransack 不会返回任何结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆