Multiple kind of relationships, Howto?

Hi there,

I am newbie on RoR and I am wondering how to solve the following
situation using “has_x” and “belongs_to” (and eventually polymorphism
if needed).

Let say that I have a Salesman table containing salesmen :slight_smile:

Let say that I have a Customer table containing customers
information and a prefered Salesman (salesman_id)

Let say that I have an Order table, orders are linked to customers
(the order “belongs to” a customer) and to salesmen (the order have
been managed by a particular salesman (salesman_id) which is not
necessary the customer prefered salesman).

Could someone explain me how to declare models and tables (keys) so
that those relationships are working ?

Many thanks for your help!

Georges

class Salesman > ActiveRecord::Base
has_many :primary_customers, :class_name => ‘Customer’, :foreign_key
=> ‘preferred_salesman_id’
has_many :orders
has_many :customers, :through => :orders
end

Table name: salesmen
Columns: id

class Customer > ActiveRecord::Base
has_many :orders
belongs_to :preferred_salesman, :class_name =>
‘Salesman’, :foreign_key => ‘preferred_salesman_id’
has_many :salesmen, :through => :orders
end

Table name: customers
Columns: id, perferred_salesman_id

class Order > ActiveRecord::Base
belongs_to :salesman
belongs_to :customer
end

Table name: orders
columns: id, salesman_id, customer_id

c = Customer.find(1)
c.salesmen # => array of all salesmen affiliated with any order
c.order[0].salesman # => salesman affiliated with a specific order
c.preferred_salesman # => the guy that cuts the best deals

s = Salesman.find(1)
s.primary_customers # => all customers for whom the salesman has
completely pulled the wool over their eyes
s.customers # => all customers affliated with any order
s.orders[0].customer # => customer associated with a specific order

Regards,
Ryan

Ryan, that’s a great help! Thanks!

Regards,

Georges

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs