开发者

Rails ActiveRecord: Is a combined :include and :conditions query possible?

开发者 https://www.devze.com 2022-12-21 05:57 出处:网络
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 2

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?


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]
)


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])
0

精彩评论

暂无评论...
验证码 换一张
取 消