February 2012
3 posts
2 tags
scope vs class method
In my last post I talked about the need to use lambdas in all scopes that call an existing scope that uses a lambda. An alternative to this is to use class methods instead of scope. So instead of: scope :active, lambda { started.unfinished } Use this: def self.active started.unfinished end Now, the active class method doesn’t need to know that started or unfinished scopes use a...
Feb 27th
3 tags
Beware of chaining lambda scopes
Here’s a gotcha to watch out for! Let’s say you have these scopes in your Rails 3 project: scope :started, lambda { where("starting_at <= ?", Time.now) } scope :unfinished, lambda { where("ending_at > ?", Time.now) } When you call either of these scopes, because you have used lambda, the value of the lambda is re-evaluated each time so that Time.now is dynamic. That’s...
Feb 23rd
1 note
1 tag
Check SQL from Rails scopes
To see the sql generated by a scope method in Rails 3 use the to_sql method. For example: Post.current.to_sql => "SELECT `posts`.* FROM `posts` WHERE (created_at > '2012-02-22')"
Feb 22nd