Rails 2アプリケーションにいくつかのクラスがありGroupますgroup_items。それぞれgroup_itemにポリモーフィックìtem:userまたはがあり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
すべてが完璧に機能します。しかし、私はこの関数を使用することができます:
@my_group.users << @my_user
@my_group.contacts << @my_contact
関連付けはこれを行うには複雑すぎるようです:
ActiveRecord::RecordInvalid for GroupItem: item_type must be filled
関数をオーバーライドするなど、この関数を使用する方法はありますGroup users<<か?
よろしく