How to use filter in Model
A model named Post, corresponding to po开发者_开发百科sts table in the db. Post.find_within_4_days
can get me the last 4 days posts. All my following operation would be based on the past 4 days posts. I would like it to be filtered or defined somewhere, so I can just reference it instead of repeating Post.find_within_4_days
everywhere. How do I do in Post model?
Assuming you're using Rails 3, you could use a name scope like this:
class Post < ActiveRecord::Base
scope :within_4_days, where(# however you find your 4 day old posts #)
end
You could then use Post.within_4_days
everywhere.
If you want only the posts of the last 4 days anywhere, you could set up a default scope instead:
class Post < ActiveRecord::Base
default_scope where(# however you find your 4 day old posts #)
end
after which (for example) Post.all
would only return the posts of the last 4 days.
Even more flexible:
class Post < ActiveRecord::Base
scope :within, lambda { |time| where("created_at > ?", Time.zone.now - time }
end
Post.within(4.days)
default_scope
and scope
are great options for your case,
refer to this wonderful site
精彩评论