returning an ActiveRecord::Relation from a has_many association

136 views
Skip to first unread message

Epoch

unread,
Aug 22, 2011, 2:29:02 AM8/22/11
to Ruby or Rails Oceania
Hi guys,

ActiveRecord in rails3 has a nice improvement where most of the API
returns a ActiveRecord::Relation so you can chain things together.

> Asset.where(:project_id => 1).class => ActiveRecord::Relation

One exception at the moment when using an association, it returns an
Array:

class Project
has_many :assets
end

> Project.first.assets.class => Array

The problem with this is we lose chain-ability, which means I can't do
things like this:

> @project = Project.first
> @project.assets.where(:active => true)

though I can get the same thing with something like this

> Asset.where(:project_id => 1, :active => true)

Personally I prefer lazy loading and chaining and was wondering if
it's possible with associations, or am I missing something, any
thoughts?

Daniel

Darcy Laycock

unread,
Aug 22, 2011, 2:30:55 AM8/22/11
to rails-...@googlegroups.com
AR is deceiving and actual returns a proxy that passes .class to the loaded data.

Try this: @project.assets.where(:active => true).class

It should be what you expect (e.g. they are chainable in the same fashion)

Ryan Bigg

unread,
Aug 22, 2011, 2:31:09 AM8/22/11
to rails-...@googlegroups.com
Actually, it's not Array. It pretends to be an Array.

You are still able to do Project.first.assets.where(...).
--
You received this message because you are subscribed to the Google Groups "Ruby or Rails Oceania" group.
To post to this group, send email to rails-...@googlegroups.com.
To unsubscribe from this group, send email to rails-oceani...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rails-oceania?hl=en.

Reply all
Reply to author
Forward
0 new messages