2011-10-11 48 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天的帖子。