1

I am working with the RailsCast on token input and am trying to cleanup a query method for Postgres. I found this post for making my query DB-agnostic.

My method:

  def self.tokens(query)
    t = Language.arel_table
    languages = Language.where(t[:name].matches("%#{query}%"))
    if languages.empty?
      [{id: "<<<#{query}>>>", name: "New: \"#{query}\""}]
    end
  end

Returns

:001 > Language.tokens('Ru')
   (0.8ms)  SELECT COUNT(*) FROM "languages"  WHERE ("languages"."name" ILIKE '%Ru%')

But if I use return instead of language =, I get the correct query:

  def self.tokens(query)
    t = .arel_table
    return Language.where(t[:name].matches("%#{query}%"))
  end

:001 > Language.tokens('Ru')
  Language Load (0.9ms)  SELECT "languages".* FROM "languages"  WHERE ("languages"."name" ILIKE '%Ru%')

It's probably something obvious, but I cannot figure out why the first method is selecting count instead of all of the rows in the `languages' table db. I would really like to store the result of that query in a variable.

1 Answer 1

1

It's because the where is resolved as lazily as it possibly can be (not until it is absolutely needed). In your case it needs it when you:

  1. Explicitly return
  2. Check empty?

The reason it is doing the count, is to determine via the count whether it is empty.

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

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.