1

我在Rails 2应用程序中有一些类:Group有一些group_items. 每个group_item都有一个多态的ìtem:usercontact.

class Group < AR::Base
  has_many :group_items
  has_many :users,    :through => :group_items
  has_many :contacts, :through => :group_items
end

class GroupItem < Ar::Base
  belongs_to :group
  belongs_to :item, :polymorphic => true
  belongs_to :users :conditions =>
      [ "#{GroupItem.table_name}.item_type = ? ", User.to_s ],
      :foreign_key => 'item_id'
  belongs_to :contacts :conditions =>
      [ "#{GroupItem.table_name}.item_type = ? ", Contact.to_s ],
      :foreign_key => 'item_id'
  validates_presence_of :group_id, :item_id, :item_type
end

一切都很完美。但我可以使用这个功能:

@my_group.users << @my_user
@my_group.contacts << @my_contact

该关联似乎太复杂而无法执行此操作:

ActiveRecord::RecordInvalid for GroupItem: item_type must be filled

有没有办法使用这个功能,比如覆盖这个Group users<<功能?

问候

4

1 回答 1

1

我找到了一个漂亮的解决方案,使用关联扩展

has_many :users, :through => :group_items do
  def <<(user)
    group_item = proxy_owner.group_items.create({ :item => user })
    return false if !group_item.valid?
    return proxy_target
  end
end
于 2013-04-16T09:27:54.593 回答