【发布时间】:2012-01-14 04:05:45
【问题描述】:
我有一个模型 Shop 和一个模型 Customer。一家商店可以有很多顾客和一个顾客 可以从很多商店买东西。对于这种关系,我创建了一个连接模型 ShopCustomers。
create_table :shop_customers do |t|
t.integer :shop_id
t.integer :customer_id
t.timestamps
end
型号
class Shop < ActiveRecord::Base
has_many :shop_customers, :dependent => true
has_many :customers, :through => shop_customers
has_many :customers_groups
end
class Customer < ActiveRecord::Base
has_many :shop_customers, :dependent => true
has_many :shops, :through => shop_customers
belongs_to :customers_group_membership
end
class ShopCustomer < ActiveRecord::Base
belongs_to :shop
belongs_to :customer
end
店主希望能够对客户进行分组,因此我添加了另一个 为客户组建模。
class CustomersGroup < ActiveRecord::Base
belongs_to :shop
end
客户通过另一个加入模型添加到一个组中。
create_table :customers_group_memberships do |t|
t.integer :customers_group_id
t.integer :customer_id
end
class CustomersGroupMembership < ActiveRecord::Base
has_many :customers
belongs_to :customers_group
end
这是建立这种关系的正确方式吗?或者这是一个秘诀 对于厄运,我是否错过了一些会使这不起作用的东西。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 database-design activerecord entity-relationship