2011-10-11 41 views
1

名为Post的模型,对应于数据库中的帖子表。 Post.find_within_4_days可以给我最后4天的职位。我之后的所有操作都是基于过去4天的职位。我希望它被过滤或定义在某个地方,所以我可以参考它,而不是随处重复Post.find_within_4_days。我如何在Post模型中做?如何在模型中使用过滤器

回答

2

更灵活:

class Post < ActiveRecord::Base 
    scope :within, lambda { |time| where("created_at > ?", Time.zone.now - time } 
end 

Post.within(4.days) 
3

假设你正在使用Rails 3,你可以使用一个名字的范围是这样的:

class Post < ActiveRecord::Base 
    scope :within_4_days, where(# however you find your 4 day old posts #) 
end 

,那么你可以无处不在使用Post.within_4_days

如果只希望最后4天的帖子的任何地方,你可以设置一个默认的范围,而不是:

class Post < ActiveRecord::Base 
    default_scope where(# however you find your 4 day old posts #) 
end 

之后

(例如) Post.all只会返回的最后4天的帖子。