Question

I'm just starting to get familiar with scopes and i see that they can be written using strings OR hash notation.

Example from the rails docs:

scope :dry_clean_only, joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true)

This could also be written as:

scope :dry_clean_only, joins(:washing_instructions).where(:washing_instructions => { :dry_clean_only => true })
  • How do you choose which one to use?
  • Are there performance implications?
  • Is there a "rails way"? (the docs sort of sprinkle both usages)

thanks!

Was it helpful?

Solution

Personally I try to use the hash syntax whenever possible, and use a string when it's unavoidable.

scope :plus_size, where(:plus_size => true)

and

scope :similar_name, lambda{ |name| where('name LIKE ?', "%#{name}%") }

I worry about writing my SQL wrong, so the less of it I write the better (such as the example above, which doesn't escape extra %'s in the string).

OTHER TIPS

As far as which one to chose, it's really a matter of preference. I personally prefer the hash syntax since you can scan it and easily see which parameters are for which columns. The hash syntax only works for equality queries, so you will need to use the string format for more complex queries anyway.

I'm willing to bet that the performance difference is negligible since it's converted to an SQL query. Hitting the database and processing the result is going to be where most of the processing time takes place, and will be identical in both cases.

If you want to benchmark them, you can use rails benchmark.

rails benchmarker "Model.joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true)" "Model.joins(:washing_instructions).where(:washing_instructions => { :dry_clean_only => true })"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top