has_many_and_belongs_to自加入关联和条件has_many

时间:2013-04-09 19:58:19

标签: ruby-on-rails-3 associations self-join

我们有这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

因此,只有customer可能包含多个订单而supplier无法关联任何Order

有没有办法实现这个目标?或者我必须将Group模型拆分为CustomerSupplier模型?

谢谢!

0 个答案:

没有答案