brad
brad

Reputation: 9773

Can I use an activerecord relation to find nested attributes?

Sorry if my question is poorly worded. I'm struggling to express it well. Lets try it in code!

I have a client model that has_many projects. If I have an ActiveRecord relation generated like so;

clients = Client.where(':sign_up_time < ?', Time.now)

and I want to get a list of all of the projects belonging to the clients returned in this relation, how would I go about it? I can do it in Ruby easily enough and get an array of projects returned, e.g.

projects = clients.inject([]) {|proj,cli| proj << cli.projects}.flatten

which is absolutely fine, but I thought there might be a nice clean way of doing this in ActiveRecord.

The important thing is that I want to use the clients object as my starting point.

Upvotes: 0

Views: 1013

Answers (2)

Andrew Kuklewicz
Andrew Kuklewicz

Reputation: 10701

I believe what you want is a join, read all about it:

http://guides.rubyonrails.org/active_record_querying.html#joining-tables

Project.joins(:clients).where(:clients=>'sign_up_time < ?', Time.now)

Upvotes: 3

Andrew Marshall
Andrew Marshall

Reputation: 96944

This isn't really ActiveRecord, but doing the following is somewhat of an idiom for doing this:

projects = Client.where(':sign_up_time < ?', Time.now).map(&:projects).flatten

this is pretty much the same as what you have, but much more cleanly written. You could also do something this, though:

clients = Client.where(':sign_up_time < ?', Time.now)
projects = Project.where(:client_id => clients)

This results in projects being an ActiveRecord::Relation rather than an array, which can be more useful. It's also a more SQL-oriented approach, which can be faster.

Upvotes: 2

Related Questions