Search code examples
activerecordruby-on-rails-3associationsarel

Is it possible to get the ActiveRecord::Relation object for an association


  1. Do association methods, such as those defined by has_many and belongs_to utilize ActiveRecord::Relation?

  2. 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.


Solution

  • For a few minutes I used the where(nil) hack, then I had a brainwave and tried something random:

    User.first.posts.scoped
    

    That's it! :D

    Yeah, Rails + Arel is really poorly documented. Looking forward to it maturing to the point where I can actually look things up and get actual answers.