Harsha M V
Harsha M V

Reputation: 54949

Rails Search Query for LIKE

I am trying to do a Search Query with the LIKE

I have the following Form

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

Controller

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

    render plain: @venues.to_yaml

Error

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

Upvotes: 1

Views: 2131

Answers (5)

Carlos Morales
Carlos Morales

Reputation: 1149

For old rails is:

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

Upvotes: 2

Milind
Milind

Reputation: 5112

simple and safe way to avoid sql injection... When you need to find records based on a condition that involves the use of LIKE '%value%' (it's going to be very slow since MySQL won't use an index for this query), try something like the following:

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

Upvotes: 0

Nithin
Nithin

Reputation: 3699

Try this,

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

2 things, to avoid sql injection use ? and % term % for searching in query

Upvotes: 4

Eyeslandic
Eyeslandic

Reputation: 14890

This is the way I do it. Using ? lets Rails take care of sql injection stuff.

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

Upvotes: 5

marcgg
marcgg

Reputation: 66436

The correct syntax would be name LIKE '%ooty%', doing a LIKE without % is the same as =.

Upvotes: 2

Related Questions