Pregunta

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?)

¿Fue útil?

Solución

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.

Otros consejos

You need to add the % sign to your SQL query

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

you can achieve this with Journal.where("headline LIKE ?", "%#{params[:query]}%")

If you want to do a case-insensitive search and you're using Postgres, use ILIKE instead of LIKE: Journal.where("headline ILIKE ?", "%#{params[:query]}%")

Adding this to hopefully save someone else the few minutes of frustration and embarrassment I just had, wondering why my lower-case search term wasn't returning any results for a title field where most words are capitalized.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top