I am newbie on RoR and I am wondering how to solve the following
situation using "has_x" and "belongs_to" (and eventually polymorphism
Let say that I have a Salesman table containing salesmen
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!
class Salesman > ActiveRecord::Base
has_many :primary_customers, :class_name => 'Customer', :foreign_key
has_many :customers, :through => :orders
Table name: salesmen
class Customer > ActiveRecord::Base
belongs_to :preferred_salesman, :class_name =>
'Salesman', :foreign_key => 'preferred_salesman_id'
has_many :salesmen, :through => :orders
Table name: customers
Columns: id, perferred_salesman_id
class Order > ActiveRecord::Base
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.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.customer # => customer associated with a specific order
Ryan, that's a great help! Thanks!