how do i define a named_scope to return all the records that were created within the last 7 days, and then how do i use that named scope in a controller?
A:
You need to pass named_scope a proc so it will be evaluated every time the call to named_scope is run. Otherwise if you specify Time.now it will run once (on first call) and be "cached" until the app is restarted.
named_scope \
:this_week,
:conditions => [
%created_at > :time!,
proc {{:time => Time.now}}
]
You can call the named_scope like @ar_object.this_week
TonyLa
2008-11-25 18:12:58
that example throws errors. "unkown type of %string %created_at"
Jason Miesionczek
2008-11-25 18:20:18
+4
A:
I would recommend watching the Railscast Episode on named_scope.
Ideally, the code you're looking for would be:
named_scope :recent,
lambda { |*args| {:conditions => ["created_at > ?", (args.first || 7.days.ago)]} }
This will allow you to pass a parameter to the named scope or it will default to the previous 7 days.
You would call it using:
MyModel.recent
mwilliams
2008-11-25 18:22:02