D. v. Baboon
D. v. Baboon

Reputation: 53

Are these Rails query syntaxes interchangable?

>scope :a, -> { joins(:b).where('bs.c': false) }

>scope :a, -> { joins(:b).where('bs.c = ?', false) }

Just wanted to ask whether those 2 lines do the same thing? The first one seemed to work fine in development but gave me a syntax error when I tried to push to Heroku. Is the first one deprecated?

Upvotes: 0

Views: 40

Answers (2)

Frederick Cheung
Frederick Cheung

Reputation: 84182

Only Ruby 2.2 and above allow use the JSON like hash syntax with quoted keys, ie

{'foo' : bar}

Instead of

{foo: bar}

Of course in your case not quoting the key probably won't work either because of the . in the key.

This suggests you are running different Ruby versions locally and on heroku.

Other than that, they should be equivalent.

Upvotes: 0

Chris Peters
Chris Peters

Reputation: 18090

I believe these are more interchangeable, without syntax errors:

scope :a, -> { joins(:b).where(bs: { c: false }) }

scope :a, -> { joins(:b).where('bs.c' => false }) }

scope :a, -> { joins(:b).where('bs.c = ?', false) }

scope :a, -> { joins(:b).where('bs.c = :q', { q: false }) }

Personally, the first line is my preferred because you can list several columns within that nested hash without needing to keep repeating the table name/alias.

Upvotes: 1

Related Questions