名爲Post的模型,對應於數據庫中的帖子表。 Post.find_within_4_days
可以給我最後4天的職位。我之後的所有操作都是基於過去4天的職位。我希望它被過濾或定義在某個地方,所以我可以參考它,而不是隨處重複Post.find_within_4_days
。我如何在Post模型中做?如何在模型中使用過濾器
1
A
回答
2
更靈活:
class Post < ActiveRecord::Base
scope :within, lambda { |time| where("created_at > ?", Time.zone.now - time }
end
Post.within(4.days)
1
default_scope
和scope
是你的情況偉大的選擇, 請參閱本wonderful site
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天的帖子。
相關問題
- 1. 如何在ng模型中使用日期過濾器?
- 2. 如何使用從模型過濾器在我的路線
- 3. 如何使用或使用Django的模型過濾器系統?
- 4. 如何在angularjs中過濾ng模型
- 5. 如何在odata模型讀取操作中應用過濾器?
- 6. 如何在views.py中使用url參數過濾模型(用戶)?
- 7. 使用ReferenceProperties過濾模型
- 8. 如何使用自定義模型過濾器過濾表單數據
- 9. 您如何在模塊化控制器中使用過濾器?
- 10. 如何過濾模型?
- 11. Ember.js - 如何過濾模型?
- 12. 如何在ElasticSearch中使用過濾器?
- 13. 如何在jGit中使用過濾器?
- 14. 如何在Grails中使用過濾器
- 15. 如何在模型過濾器中過濾日期時間的星期幾?
- 16. 如何使用意圖過濾器來過濾文本模式
- 17. 在Django中過濾模型
- 18. Django - 過濾器模型
- 19. 實施模型過濾器
- 20. Django模型manytomany過濾器
- 21. django模型過濾器validate_unique
- 22. 如何在javascript中使用過濾器函數過濾對象?
- 23. 如何過濾模型中的數據?
- 24. 如何在mule請求者模塊中使用過濾器?
- 25. 如何在django模板中使用if條件的過濾器
- 26. 如何在Django模板過濾器中使用Sekizai JavaScript塊?
- 27. 如何在服務模板中不使用原始過濾器
- 28. 如何在jQuery中使用Django模板標籤和過濾器?
- 29. 如何在模態實例中使用過濾器
- 30. 如何在操作過濾器後更新示波器模型?