Search code examples
ruby-on-railspolymorphic-associationsruby-on-rails-2model-associations

Override has_many << function


I have some classes in a Rails 2 application: a Group have some group_items. Each group_item has a polymorphic ìtem : user or contact.

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

Everything works perfectly. But I would be able to use this functions :

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

The association seems to be too complicated to do this :

ActiveRecord::RecordInvalid for GroupItem: item_type must be filled

Is there any way to use this function, like override the Group users<< function ?

Regards


Solution

  • I found a beautiful solution, using 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