Rails搜索LIKE的查询

时间:2014-08-25 12:48:16

标签: ruby-on-rails search

我正在尝试使用LIKE

进行搜索查询

我有以下表格

<%= form_tag "/search", :method => 'get',  :id => 'header-search', :class => 'navbar-form navbar-left', :role => 'search' do %>
  <div class="form-group">
    <%= text_field_tag :query, params[:query] ,:class => "form-control header-search-input", :placeholder => "Looking for..." %>
  </div>
<% end %>

控制器

@query = params[:query]
    # @venues = Venue.where({ :name => "#@query" })
    @venues = Venue.find(:all, :conditions => ["name LIKE #{@query}"])

    render plain: @venues.to_yaml

错误

Couldn't find all Venues with 'id': (all, {:conditions=>["name LIKE ooty"]}) (found 0 results, but was looking for 2)

5 个答案:

答案 0 :(得分:5)

这就是我这样做的方式。使用?让Rails处理sql注入的东西。

@venues = Venue.where('name LIKE ?', "%#{@query}%")

答案 1 :(得分:4)

试试这个,

 @venues = Venue.where("name like ?", "%#{@query}%")

2件事,为避免sql注入使用?% term %进行查询搜索

答案 2 :(得分:2)

正确的语法是name LIKE '%ooty%',没有LIKE的{​​{1}}与%相同。

答案 3 :(得分:2)

旧轨道是:

    @venues= Venue.find(:all,:conditions=>['name LIKE ?',"%#{@query}%"])

答案 4 :(得分:0)

避免sql注入的简单安全的方法...  当您需要根据涉及使用LIKE'%value%'的条件查找记录时(由于MySQL不会对此查询使用索引,因此速度非常慢),请尝试以下操作:

    @query = params[:query]
    @venues = Venue.find(:all, :conditions=> ["name like ?",  '%'+@query +'%'])