Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 507
William Jones Avatar asked Feb 21 '10 04:02

William Jones


People also ask

How do you avoid N 1 queries ActiveRecord?

You can avoid most n+1 queries in rails by simply eager loading associations. Eager loading allows you to load all of your associations (parent and children) once instead of n+1 times (which often happens with lazy loading, rails' default). As seen above, . includes allows nested association eager loading!

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.

How can we use two databases to a single application rails?

Rails 6.0 ships with all the rails tasks you need to use multiple databases in Rails. Running a command like bin/rails db:create will create both the primary and animals databases.

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module...


2 Answers

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]
)
like image 50
Peter Brown Avatar answered Oct 01 '22 11:10

Peter Brown


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])
like image 35
jdl Avatar answered Oct 01 '22 11:10

jdl