Do association methods, such as those defined by
has_many
andbelongs_to
utilizeActiveRecord::Relation
?If so, is it possible to get the
ActiveRecord::Relation
object that is being used.
We're all aware that Rails 3 is heavily using ActiveRecord::Relation
objects, and Arel::Relation
objects in the background, when creating queries using the Query Interface. Whenever we use the select
, joins
, etc. methods of the Query Interface, a ActiveRecord::Relation
object is returned. However, this doesn't seem to be the case when calling an association method of a model. Instead, the query is executed immediately and an instance, or an array of instances, of the associated model is returned.
Consider the following models:
post.rb
class Post < ActiveRecord::Base
belongs_to :user
end
user.rb
class user < ActiveRecord::Base
has_many :posts
end
Example:
u = User.first
u.posts
Calling u.posts
returns an array of posts, not an instance of ActiveRecord::Relation
. I'm wondering if it's possible to get the ActiveRecord::Relation
that is being used by the association, if it is being used at all, perhaps by using Arel::Table
?
My reasoning for wanting the ActiveRecord::Relation
should be obvious: It is because I want to chain off the existing association and manipulate the query to suit a different purpose.