Skip to content Skip to sidebar Skip to footer

Trying To Create A Rails Model Scope Query For Records Since Date X, Use A Lambda?

I think I will want to use combine a model level finder with a lambda. named_scope :recent_snaps, lambda {|since_when| {:conditions=>{:created_at >= since_when}}} but I am n

Solution 1:

If you're on Rails 3 (as you presumably are, given the question's tags) you should be using scope rather than named_scope and where rather than conditions. Additionally, you can't use >= in a hash.

Your finished scope should look something like this:

scope :recent_snaps, lambda { |since_when| where("created_at >= ?", since_when) }

Solution 2:

To complement Alex's answer: for the looks of the query you're trying, I think you'll like squeel:

scope :recent_snaps, lambda { |since_when| where{created_at >= since_when} }

Solution 3:

Just other ways to achieve the same (at least in rails 3.1)

in plain rails

scope :recent_snaps, ->(since_when) { where("created_at >= ?", since_when) }

rails+squeel

scope :recent_snaps, ->(since_when) { where{created_at >= since_when} }

Post a Comment for "Trying To Create A Rails Model Scope Query For Records Since Date X, Use A Lambda?"