How can an ActiveRecord::Relation object call class methods?
class Project < ActiveRecord::Base has_many :tasks end class Task < ActiveRecord::Base belongs_to :project def self.initial_tasks # class methods # here return initial tasks end end
Now we can call :
Project.first.tasks.initial_tasks # how it works
initial_tasks
is a class method and we can't call class methods on an object.
Project.first.tasks
returns an ActiveRecord::Relation object, so how could it be able to call initial_tasks
?
Please explain.
The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
There's not much documentation on the application on class methods to ActiveRecord::Relation
objects, but we can understand this behavior by taking a look at how ActiveRecord scopes work.
First, a Rails model scope will return an ActiveRecord::Relation
object. From the docs:
Class methods on your model are automatically available on scopes. Assuming the following setup:
class Article < ActiveRecord::Base scope :published, -> { where(published: true) } scope :featured, -> { where(featured: true) } def self.latest_article order('published_at desc').first end def self.titles pluck(:title) end end
First, invoking a scope returns an ActiveRecord::Relation
object:
Article.published.class #=> ActiveRecord::Relation Article.featured.class #=> ActiveRecord::Relation
Then, you can operate on the ActiveRecord::Relation
object using the respective model's class methods:
Article.published.featured.latest_article Article.featured.titles
It's a bit of a roundabout way of understanding the relationship between class methods and ActiveRecord::Relation
, but the gist is this:
ActiveRecord::Relation
objectsActiveRecord::Relation
objects have access to class methodsIf 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