0

I'm having trouble understanding advanced search with two string pls help

error coms like:

undefined method `where' for #

<ActiveRecord::QueryMethods::WhereChain:0x007f2dcc0da5b0>

in the search model

search.rb

def search_books
  books = Book.all
  books = books.where{["name LIKE ?","%#{keywords}%"]}if keywords.present?
  books = books.where{["category LIKE ?","%#{keywords}%"]}if keywords.present?

  return books
end
1
  • It seems like your first query is returning nil. can you log the output of your first query? Commented Feb 9, 2018 at 22:27

2 Answers 2

2

Use like the below:

keywords = 'test'

with AND:

Book.where("name LIKE '%#{keywords}%' AND category LIKE '%#{keywords}%'") if keywords.present?

with OR:

Book.where("name LIKE '%#{keywords}%' OR category LIKE '%#{keywords}%'") if keywords.present?

But this usage is not safe. Read following warning from Rails documentation:

Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, Client.where("first_name LIKE '%#{params[:first_name]}%'") is not safe.

Sign up to request clarification or add additional context in comments.

Comments

1

If you wanted to use a scope for searching you could do something like this in your controller

    def index     
      @books = Book.all

      # scopes
      if params[:keyword].present? 
        @books = @books.by_keyword(params[:keyword])
      end
   end

then in your model do the below

  scope :by_keyword, ->(keyword) { where('name LIKE ? AND category LIKE ?', "%#{keyword}%", "%#{keyword}%").order(updated_at: :desc) if keyword.present? }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.