开发者

When using a Scope, when should one use hash notation vs a string?

开发者 https://www.devze.com 2023-04-05 14:35 出处:网络
I\'m just starting to get familiar with scopes and i see that they can be written using strings OR hash notation.

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!


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).


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 })"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号