2

我遇到了一个非常棘手的问题。这是我的模型:

class Entry < ActiveRecord::Base
  default_scope :order => 'published_at DESC'
  named_scope :published, :conditions => ["published_at < ?", Time.zone.now], :order => 'published_at DESC'
  belongs_to :blog
end

现在如果我这样做

@entries = Entry.published.paginate_by_blog_id @blog.id,
        :page => params[:page],
        :order => 'published_at DESC', 

除非我将 published_at 向后移动一小时,否则它不会返回帖子。但:

@entries = Entry.paginate_by_blog_id @blog.id,
        :page => params[:page],
        :conditions => ["published_at < ?", Time.zone.now], 
        :order => 'published_at DESC', 

它工作正常!

我要疯了,有人知道从哪里开始调试吗?

4

1 回答 1

7

命名范围不是动态运行的,因此 Time.zone.now 是类加载时的值。如果您希望命名范围在每次调用时使用不同的值,则条件需要是 lambda 的结果。

看看http://railscasts.com/episodes/108-named-scopehttp://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-查找器功能

例如:

named_scope :recent, lambda { { :conditions => ['created_at > ?', 1.week.ago] } }

这样每次调用范围时都会计算 1.week.ago。

于 2009-11-10T12:43:13.753 回答