views:

42

answers:

1

I've seen this problem before but I'm not sure how to solve it.

Say I have:

class Notification < ActiveRecord::Base
  scope :current_notifications, where("starts_at <= ?", Time.now).where("ends_at >= ?", Time.now).limit(1)
end

So the scope is being calculated from the time that the server started, any thoughts on how to fix instances like this?

+5  A: 

You need a lambda. (This creates an anonymous method, which Rails then calls each time the scope is called.)

class Notification < ActiveRecord::Base
  scope :current_notifications, lambda {
    now = Time.now
    where("starts_at <= ?", now).where("ends_at >= ?", now).limit(1)
  }
end
fig
oddly enough I get an error:`syntax error, unexpected '=', expecting '|' scope :current_notifications, lambda { |now = Time.now|` then there is a caret pointing up at space between `=` and `Time.now`
Joseph Silvashy