Reputation: 5178
As an example:
A company has_many employees
an employee has_many tasks
I want to get all the tasks in descending order. Ideally, I'd like to do something like Company.all.employees.tasks.order('created_at desc')
. Unfortunately, by the time I get through employees
, I now have an array of ActiveRecord objects. I've been running into this issue for a while, and I've just been using map
and collect
, but sorting in descending order makes for more overhead than I want. This can be done with a SQL query so I'm sure I can do it in ActiveRecord, but my research hasn't helped much.
EDIT:
The solution should work for any number of models. For example, if a task has_many items
and an item has_many sub_items
ad infinitum.
Upvotes: 3
Views: 2305
Reputation: 44952
One approach you can use is to use through
class Company < ActiveRecord::Base
has_many :employees
has_many :tasks, through: :employees
end
Then a Company
will have tasks
for all of it's employees.
c
Another way to do it would be to use joins. So assuming that a Task
belongs_to
a Employee
and an Employee
belongs_to
a Company
c = Company.first # for a company...
tasks = Task.where(companies:{id: c.id}).joins(employee: :company)
So I am asking for all tasks where the companies
table (and yes it is the table in the where). We use the joins to establish the tables that must be joined to.
Upvotes: 5