覆盖has_many<<功能

时间:2013-04-16 08:39:32

标签: ruby-on-rails polymorphic-associations ruby-on-rails-2 model-associations

我在 Rails 2 应用程序中有一些类:Group有一些group_items。每个group_item都有一个多态ìtemusercontact

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<<功能?

此致

1 个答案:

答案 0 :(得分:0)

我使用Association Extensions找到了一个漂亮的解决方案

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