我们有这 3 个模型:
class Group < ActiveRecord::Base
attr_accessible :name
has_many :users
has_and_belongs_to_many :suppliers,
:class_name => "Group",
:foreign_key => "customer_id",
:association_foreign_id => "supplier_id"
has_and_belongs_to_many :customers,
:class_name => "Group",
:foreign_key => "supplier_id",
:association_foreign_id => "customer_id"
has_many :orders, :as => :orderable
validates :name => :presence => true
end
class User < ActiveRecord::Base
attr_accessible :email, :name
has_many :orders, :as => :orderable
belongs_to :group
validates :email, :name, :group_id, :presence => true
end
class Order < ActiveRecord::Base
belongs_to :orderable, :polymorphic => true
validates :orderable_id, :presence => true
end
根据自联接Group
模型,我们有 2 种“类型”的组:customers
和suppliers
。
现在我们希望has_many :orders, :as => :orderable
关联应该只存在于customer
组类型而不是suppliers
.
因此,只有 acustomer
可以有很多订单,而 asupplier
不能有任何Order
关联。
有没有办法做到这一点?或者我必须将Group
模型拆分为Customer
和Supplier
模型?
谢谢!