0

我们有这 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 种“类型”的组:customerssuppliers

现在我们希望has_many :orders, :as => :orderable关联应该只存在于customer组类型而不是suppliers.

因此,只有 acustomer可以有很多订单,而 asupplier不能有任何Order关联。

有没有办法做到这一点?或者我必须将Group模型拆分为CustomerSupplier模型?

谢谢!

4

0 回答 0