Modeling question

Hi,

I have 3 models - salesperson, customer, purchased_product.

salesperson has_many customers.
customer has_many purchased_products.

I can do

salesperson.customers
salesperson.customers[0].purchased_products

But I want to do

salesperson.purchased_products

Basically it means

salesperson.customers.inject([]) {|memo, c|
memo += c.purchased_products
}

I tried

class Rep < ActiveRecord::Base
has_many :customers
has_many :purchased_products, :through => :customers
end

But it didn’t work.(Am I missing something?)
I think :finder_sql option will work but I don’t feel that it’s best
option.

Can anyone help me?
Thanks.

Sam

Sam, I am assuming you have the following…

class Salesperson < ActiveRecord::Base
has_many :customers
has_many :purchased_products, :through => :customers
end

class Customer < ActiveRecord::Base
belongs_to :salesperson
has_many :purchased_products
end

class PurchasedProduct < ActiveRecord::Base
belongs_to :customer
end

…and also:

table “purchased_products” with “customer_id”
table “customers” with “salesperson_id”

And what you do is:

Salesperson.find(:first).purchased_products

This works as advertised. I’ve just tried id. Do you get an error in
the log?

Or did you just not get the results you expected?
I ask, because your model is flawed as it only allows each Product to
be purchased by ONE customer only. Same goes for Customers and
Salespeople. Each Customer belongs to only ONE Salesperson.

Did you mean to us has_and_belongs_to_many in these occasions? Or
even a “Customer has_many :products, :through => :purchases” and
“Salesperson has_many :customers, :through => :sales” and utilise the
two join models Purchases, Sales?

-christos

Hi Christos,

Christos Z. wrote:

Sam, I am assuming you have the following…

Your assumption is correct in every way.

This works as advertised. I’ve just tried id. Do you get an error in
the log?

You’re right.
My test was wrong.
I tested it in script/console.
After I add purchased_products, I didn’t reload (salesperson.reload).
I thought that it’s done automatically.

Thank you very much.

Sam