Skip to content

Instantly share code, notes, and snippets.

@amiel
Created May 15, 2012 21:07
Show Gist options
  • Save amiel/2705150 to your computer and use it in GitHub Desktop.
Save amiel/2705150 to your computer and use it in GitHub Desktop.
Which is better?
t = Collection.arel_table
where(t[:public].eq(true).or(t[:user_id].eq(user.id)))
# or
where('public = ? OR user_id = ?', true, user.id)
@itstommymorgan
Copy link

For most cases I would strongly prefer the latter because it's significantly easier to read.

@amiel
Copy link
Author

amiel commented May 15, 2012

@duwanis I agree, but am curious if anyone has a good argument for the first

@itstommymorgan
Copy link

The more parameters you have for the query, the more the first form becomes preferable to the second because it's easier to tell which value should be mapped to which param.

If you're running a query that complicated, though, I'd say you need to be thinking about it differently anyway.

@amiel
Copy link
Author

amiel commented May 15, 2012

Good point. Another option if there are lots of parameters is to use the hash syntax:

where('public = :public OR user_id = :user_id', public: true, user_id: user.id)

@itstommymorgan
Copy link

True. I keep forgetting about that 😄

@intjonathan
Copy link

Also query builders for variable search parameters become super hairy with the second form. There's a reason arel won and it's because it scales to longer queries better.

@amiel
Copy link
Author

amiel commented May 16, 2012

@intjonathan thanks, that's a good point; building arbitrarily complex queries is pretty hairy with that second form unless it's just AND

Can you give an example of nice use of arel?

@emmanuel
Copy link

Not an issue in the simple case, but I believe that the second form will follow/respect/use aliasing of the table (as AR does sometimes with associations).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment