【问题标题】:Rails polymorphic relationship without specifying source type不指定源类型的 Rails 多态关系
【发布时间】:2023-04-06 00:26:01
【问题描述】:

在我的应用程序中,我有一个 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

【问题讨论】:

  • 您能解释一下为什么要使用some_list.list_items &lt;&lt; my_photo 而不是some_list.photos &lt;&lt; my_photo 吗?
  • 我已经编辑了我的问题以解释我为什么要这样做。
  • 能否请您展开类代码以显示继承。我假设 Photo 和 Video 继承自 ListItem,对吗?

标签: ruby-on-rails polymorphism


【解决方案1】:

一个快速的解决方案可能是:

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

【讨论】:

    猜你喜欢
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多