Do association methods, such as those defined by has_many
and belongs_to
utilize ActiveRecord::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.
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. Edit: as Mike points out, in this case ActiveRecord is a module... ActiveRecord is defined as a module in Rails, github.com/rails/rails/tree/master/activerecord/lib/…
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.
One of the primary aspects of ActiveRecord is that there is very little to no configuration needed. It follow convention over configuration. ActiveRecord is commonly used with the Ruby-on-Rails framework but you can use it with Sinatra or without any web framework if desired.
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.
in Rails 4, use .scope
or .spawn
to access the relation object instead of the CollectionProxy
. See the documentation.
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