Skip to content

Instantly share code, notes, and snippets.

@otobrglez
Created October 3, 2011 23:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save otobrglez/1260533 to your computer and use it in GitHub Desktop.
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!
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