简体   繁体   English

简单搜索仅搜索记录的最后一个单词

[英]Simple search only searching last word of record

I set up a simple search as instructed in part of railscast #240. 我按照railscast#240的一部分设置了一个简单的搜索。

in controller 在控制器中

 @reports = Report.search(params[:search]).order('created_at DESC').paginate(:page => params[:page], :per_page => 5)

in model 在模型中

  def self.search(search)
    if search
      where('apparatus LIKE ?', "%#{search}") 
    else
      scoped
    end
  end

in view 在视野中

<%= form_tag reports_path, :method => :get do %>
    <p>
        <%= text_field_tag :search, params[:search] %>
        <%= submit_tag "Search", :name => nil %>
    </p>
<% end %>

it all works... but... 这一切都有效......但......
I have a few records for example, one with "another time test" and another with "last test of time" 例如,我有一些记录,一个是“另一个时间测试”,另一个是“最后时间测试”
if i search "test" the first comes up but the second doesn't, and if i search "time" the second comes up but not the first. 如果我搜索“测试”第一个出现但第二个没有,如果我搜索“时间”第二个出现但不是第一个。 It is only seeing the last word of the record. 它只能看到记录的最后一个字。

what gives? 是什么赋予了?

You need to put a percent sign on both sides of the search term. 您需要在搜索字词的两边放置百分号。 Like so: 像这样:

where('apparatus LIKE ?', "%#{search}%")

By putting the percent sign before the search term, you're leaving everything before it as a wildcard. 通过在搜索词之前添加百分号,您可以将其中的所有内容保留为通配符。 However, you're also saying, by not putting after the search term, that nothing after this should be considered a wildcard. 但是,你也说过,不要在搜索词之后,在此之后没有任何内容应该被视为通配符。 That's why it only matching the last word. 这就是它只匹配最后一个单词的原因。

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

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