jpw
jpw

Reputation: 19257

rails 3.1 - how to do an easy query with associations (all orders for a user, through accounts)

Users has_many Accounts
Accounts belongs_to Users

Accounts has_many Orders
Orders belongs_to Account

I am trying to get a list of all the orders for a user 'u'

As expected, u.accounts gives a list of all the accounts for that user

u.accounts.joins(:orders) is incorrect, since it lists stores, not orders (seems to list the store for each order, rather than the order for each order)

Is a user has 3 accounts, and each account has 4 orders, I should have 12 rows.

Any help would be appreciated!

Upvotes: 0

Views: 48

Answers (1)

Sam Peacey
Sam Peacey

Reputation: 6034

In user.rb:

has_many :orders, :through => :accounts

Then you should be able to just do u.orders.

Upvotes: 2

Related Questions