Rails ActiveRecord:是否可以组合 :include 和 :conditions 查询?

发布于 2024-08-22 12:13:33 字数 331 浏览 3 评论 0原文

想象一下我有 wiki 文章,有很多修订。我想通过数据库使用 ActiveRecord 进行查询,该查询仅返回那些在过去 24 小时内更新过修订的文章。这样的事可能吗?

我想它会是这样的:

Articles.find_all(:include => :revisions, 
                  :conditions => {:revision[updated_at] => 1.week.ago..Time.now.utc})

如果这不可能,是否有某种类型的原始 SQL 我可以传递给 find_by_SQL 来实现这个目的?

Imagine I have wiki Articles, with many Revisions. I'd like to do a query with ActiveRecord through the database, which only returns those Articles which have Revisions which are updated in the past 24 hours. Is such a thing possible?

I'd imagine it'd be something like:

Articles.find_all(:include => :revisions, 
                  :conditions => {:revision[updated_at] => 1.week.ago..Time.now.utc})

If this isn't possible, is there some type of raw SQL I could pass to find_by_SQL that'd do the trick?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南巷近海 2024-08-29 12:13:33

如果您只需要文章而不需要立即加载所有修订版,则可以使用 :joins 代替。它使用较少的内存,因为它不会预加载每篇文章的所有修订。如果您要执行类似 article.revisions 之类的操作,请使用 :include 。

Article.find(:all, 
  :joins => :revisions, 
  :conditions => ["revisions.updated_at > ?", 24.hours.ago]
)

If you only need the article and don't need eager loading of all the revisions, you could use :joins instead. It uses less memory because it's not preloading all the revisions for each article. Use :include though if you will be doing something like article.revisions.

Article.find(:all, 
  :joins => :revisions, 
  :conditions => ["revisions.updated_at > ?", 24.hours.ago]
)
南街女流氓 2024-08-29 12:13:33

根据您对模型的具体命名方式,它会是这样的。

Article.find(:all, :include => :revisions, :conditions => ["revisions.updated_at > ?", 1.week.ago])

Depending on how exactly you have your models named, it's going to be something like this.

Article.find(:all, :include => :revisions, :conditions => ["revisions.updated_at > ?", 1.week.ago])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文