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

天涯浪子 提交于 2019-12-23 09:31:35

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/2304766/rails-activerecord-is-a-combined-include-and-conditions-query-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!