Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to get the ActiveRecord::Relation object for an association
    primarykey
    data
    text
    <ol> <li><p>Do association methods, such as those defined by <code>has_many</code> and <code>belongs_to</code> utilize <code>ActiveRecord::Relation</code>?</p></li> <li><p>If so, is it possible to get the <code>ActiveRecord::Relation</code> object that is being used.</p></li> </ol> <p>We're all aware that Rails 3 is heavily using <code>ActiveRecord::Relation</code> objects, and <code>Arel::Relation</code> objects in the background, when creating queries using the <a href="http://edgeguides.rubyonrails.org/active_record_querying.html#retrieving-objects-from-the-database" rel="noreferrer">Query Interface</a>. Whenever we use the <code>select</code>, <code>joins</code>, etc. methods of the Query Interface, a <code>ActiveRecord::Relation</code> 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.</p> <p>Consider the following models:</p> <p><code>post.rb</code></p> <pre><code>class Post &lt; ActiveRecord::Base belongs_to :user end </code></pre> <p><code>user.rb</code></p> <pre><code>class user &lt; ActiveRecord::Base has_many :posts end </code></pre> <p>Example:</p> <pre><code>u = User.first u.posts </code></pre> <p>Calling <code>u.posts</code> returns an array of posts, not an instance of <code>ActiveRecord::Relation</code>. I'm wondering if it's possible to get the <code>ActiveRecord::Relation</code> that is <em>being used by the association</em>, if it is being used at all, perhaps by using <code>Arel::Table</code>?</p> <p>My reasoning for wanting the <code>ActiveRecord::Relation</code> should be obvious: It is because I want to chain off the existing association and manipulate the query to suit a different purpose.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload