Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search active record for partial strings in a column

I need to perform a search on a single model Journal, after my product search results are returned.

Is there a way to search a Journal headline with only part of the full string?

def index
    @product_results = Gemgento::Search.products(params[:query])
    @editorial_results = Journal.where("headline LIKE ?", "#{params[:query]}")   
end

For example. Say my last journal object had the headline: "stack overflow blogpost" if I query active record with:

@editorial_results = Journal.where("headline LIKE ?", "stack overflow")

As I have it now, it still requires a direct match on the string.

Searching through http://guides.rubyonrails.org/active_record_querying.html it seems that this is the correct way to do this, despite the warnings of sql injection.

Is there a way to structure the search so it will return the last entry? (without using a search library?)

like image 738
SerKnight Avatar asked Apr 16 '14 16:04

SerKnight


1 Answers

You are missing the wildcard '%' before and after the search term.

def index
   @product_results = Gemgento::Search.products(params[:query])
   @editorial_results = Journal.where("headline LIKE ?", "%#{params[:query]}%")   
end

This means that anything can come before and after the query parameter.

like image 116
KPheasey Avatar answered Nov 07 '22 12:11

KPheasey