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?
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!
ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.
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.
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...
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With