[Rails] My solution to use where() as LIKE query


If you use LIKE query with where(), you write like this.

return Book.where("title like ? ", "%{query}%")

But I want to use LIKE query only if title form is filled.


In this case, I write following code.

queries = get_query_hash()
books = Book.all

title_query = queries[:title]
if title_query != ''
  books = books.where("title like ? ", title_query)

return books.where(queries)

Lazy Evaluation

Might you look that Book.all and books.where("title like ? ", title_query) execute query and return books array.
Actually they still don’t execute a query.
And they return ActiveRecord::Relation.

Queries will not executed until they are needed.

Open the rails console and try.

irb(main):001:0> Book.all.class
=> Book::ActiveRecord_Relation

irb(main):002:0> Book.first.class
  Book Load (42.9ms)  SELECT  "books".* FROM "books" ORDER BY "books"."id" ASC LIMIT $1  [["LIMIT", 1]]
=> Book(id: integer, title: text, author: string)


Ref: https://www.theodinproject.com/courses/ruby-on-rails/lessons/active-record-queries#relations-and-lazy-evaluation


メールアドレスが公開されることはありません。 * が付いている欄は必須項目です