简体   繁体   English

使用全名搜索时,Gem Ransack不会返回任何结果

[英]Gem Ransack doesn't return any results when searched with full name

I'm using Ransack with Rails 3. 我正在使用Ransack和Rails 3。

My views: 我的观点:

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

My schema: 我的架构:

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

Working on the console. 在控制台上工作。

If I have user with first_name = "Foo" , last_name = "Bar" , when I search with either one, I get the results as expected. 如果我有first_name = "Foo"last_name = "Bar" ,当我用任何一个搜索时,我得到了预期的结果。

When I search with full_name = "Foo Bar" , I get no results. 当我使用full_name = "Foo Bar"搜索时,我没有得到任何结果。

I tried changing my text_field for Ransack to: 我尝试将我的text_field更改为Ransack:

<%= f.text_field :first_name_or_last_name_or_company_or_full_name_cont

I get first_name_or_last_name_or_company_or_full_name_cont is undefined 我得到first_name_or_last_name_or_company_or_full_name_cont is undefined

is there a quick way to solve this without adding another column for full_name on my users table? 有没有一种快速解决方法,而无需在我的用户表上添加另一列full_name?

also : 还:

     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. 我想我可以在这里分割键值来搜索名字。

You have to use a Ransacker . 你必须使用Ransacker Add this in your User model: 在您的User模型中添加:

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

You can check the Ransack GitHub wiki to more examples. 您可以查看Ransack GitHub wiki以获取更多示例。

Add the following code to your model: 将以下代码添加到模型中:

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

... and the following in your view: ......以及您认为的以下内容:

<%= f.label :full_name %><br>
<%= f.search_field :full_name_cont %>

The ransacker part was taken from the Ransack wiki . ransacker部分取自Ransack维基

Tested on Rails 4.2 with PostgreSQL. 使用PostgreSQL在Rails 4.2上测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM