在我的rails应用程序中Company充当用户模型。一个公司可以有许多客户和许多雇员(汽车销售商)。
汽车销售商和顾客之间存在多对多关系。有以下问题:很多时候我必须检索与整个公司的所有约会。由于在约会模型中没有保存company_id,这可能会非常麻烦。
我是否应该在约会中包含公司的外键,并有某种形式的冗余,或者有其他简单有效的方法?
class Company < ActiveRecord::Base
has_many :customers
has_many :carseller
end
class Customer < ActiveRecord::Base
belongs_to :company
has_many :appointments
has_many :carsellers, :through => :appointments
end
class Carseller < ActiveRecord::Base
belongs_to :company
has_many :appointments
has_many :customers, :through => :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :customer
belongs_to :carseller
end
我认为你可以使用:
class Appointment < ActiveRecord::Base
belongs_to :customer
belongs_to :carseller
has_one :company, :through => :carseller
end
那么你只需要做appointment.company
就可以得到它