Created
October 3, 2011 23:25
-
-
Save otobrglez/1260533 to your computer and use it in GitHub Desktop.
rails named scopes with lambda. a.k.a. problems with date/time in scopes!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Note that scopes defined with scope will be evaluated when they are defined, rather than when they are used. For example, the following would be INCORRECT!!!: | |
scope :published, | |
where(:published => 1) | |
.where(:hidden => 0) | |
.where("publish_date <= ?", Time.now) | |
The example above would be "frozen" to the Time.now value when the model class was defined, and so the resultant SQL query would always be the same. The correct way to do this would be via a lambda, which will re-evaluate the scope each time it is called: | |
scope :published, -> { | |
where(:published => 1) | |
.where(:hidden => 0) | |
.where("publish_date <= ?", Time.now) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment