Fellow Stranger
Fellow Stranger

Reputation: 34013

Return all associated objects in collection

A Company has_many :users.

A User has_many :notes.

How can I return all notes of all users in a company?

company.users.notes

Upvotes: 1

Views: 1098

Answers (2)

jvnill
jvnill

Reputation: 29599

You can set up a has_many through association between a company and note

class Company < ActiveRecord::Base
  has_many :users
  has_many :notes, through: :users
end

Then you can just use company.notes to get all notes under a single company

Upvotes: 5

usha
usha

Reputation: 29349

company.users.collect(&:notes).flatten

Upvotes: 3

Related Questions