I'm using Rails 3.2.0
Let's say I have:
class Comment < ActiveRecord::Base
has_many :articles
end
c1 = Comment.last
then
c1.articles.class
# => Array
c1.articles.where('id NOT IN (999999)').class
# => ActiveRecord::Relation
Why is the result of an association not a type of ActiveRecord::Relation
?
It clearly is / was at some point:
c1.articles.to_orig
# undefined method `to_orig' for #<ActiveRecord::Relation:0x007fd820cc80a8>
c1.articles.class
# => Array
Certain evaluations act upon an ActiveRecord::Relation object, but inspecting the class gives a different type.
Particularly, this breaks building lazy-loaded queries when using merge
to concat multiple queries.
Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.
An instance of ActiveRecord::Base is an object that represents a specific row of your database (or might be saved into the database). Whereas an instance of ActiveRecord::Relation is a representation of a query that can be run against your database (but wasn't run yet).
Rails supports six types of associations: belongs_to.
It is an ActiveRecord::Relation
, but Rails is intentionally lying to you. You can see this already in the method calls, and continue to see it by calling ancestors
, which includes a slew of ActiveRecord classes:
c1.articles.ancestors.select { |c| c.to_s =~ /ActiveRecord/ }.size #=> 35
which shows that it is very much not an Array
.
This happens because what you’re getting back when calling c1.articles
is an ActiveRecord::Associations::CollectionProxy
*, which undefines class
(along with many other methods). This means that class
gets delegated via its method_missing
, which sends it to target
. As we can see, the class of target
here is, in fact, Array
:
c1.articles.target.class #=> Array
That is where c1.articles.class
comes from. Nevertheless, it is an ActiveRecord::Relation
.
* We can verify that it is indeed an ActiveRecord::Associations::CollectionProxy
by calling Ruby’s original class
method on the object in question: Object.instance_method(:class).bind(c1.articles).call
. This is a nice trick to verify that the object is not trying to pretend to be of a different class.
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