Rails多态关系,不指定源类型

时间:2014-01-27 14:31:01

标签: ruby-on-rails polymorphism

在我的应用程序中,我有一个可以包含照片或视频的ItemList,所以我使用多态关系来表示关联。 (请记住,除了PhotoVideo

之外,还有许多其他类
class List < ActiveRecord::Base
  has_many :list_items
  has_many :photos, through: :list_items, source: :listable, source_type: 'Photo'
  has_many :videos, through: :list_items, source: :listable, source_type: 'Video'
end

class ListItem < ActiveRecord::Base
  belongs_to :listable, polymorphic: true
end

class Photo < ActiveRecord::Base
end

class Video < ActiveRecord::Base
end

这样可行,因为我可以做像...这样的事情。

my_photo = Photo.last
some_list.photos << my_photo
some_list.photos #=> [my_photo]
some_list.videos #=> []

但有没有办法可以做到以下几点:

my_photo = Photo.last
some_list.list_items << my_photo

因为目前我收到错误:

ActiveRecord::AssociationTypeMismatch: ListItem(#70318368851760) expected, got Photo(#70318311121120)

我想这样做的原因是为了避免这种情况:

obj = get_some_object
if obj.is_a?(Photo)
  my_list.photos << obj
elsif obj.is_a?(Video)
  my_list.videos << obj
elsif
  # ...
end

1 个答案:

答案 0 :(得分:0)

快速解决方案可能是:

class List < ActiveRecord::Base
 has_many :list_items do
   def << (item)
    i = ListItem.create(listable: item)
    super i
   end
 end
 has_many :photos, through: :list_items, source: :listable, source_type: 'Photo'
 has_many :videos, through: :list_items, source: :listable, source_type: 'Video'
end