如何通过许多模型靶向多态性模型



我有4个类:

class User < ApplicationRecord
  has_many :memories
  has_many :playlists
  has_many :items, as: 'playlist_items', through: :playlists
  has_many :items, as: 'memory_items', through: :memories
end
class Item < ApplicationRecord
 belongs_to :itemable, polymorphic: true, optional: true
end
class Playlist < ApplicationRecord
  belongs_to :user
  has_many :items, as: :itemable, dependent: :destroy
  accepts_nested_attributes_for :items, allow_destroy: true
end
class Memory < ApplicationRecord
  belongs_to :user
  has_many :items, as: :itemable, dependent: :destroy
  accepts_nested_attributes_for :items, allow_destroy: true
end

我希望能够从current_user到任何类型的项目,即内存或播放列表。但是现在我只能到1套。

has_many :items, through: :playlists

我目前无法弄清楚如何在列表中进行两者。" As"似乎没有任何作用。有什么建议非常有帮助吗?

您不能与同名相同的关联,您可以专门指定源。尝试这样:

class User < ApplicationRecord
  has_many :memories
  has_many :playlists
  has_many :playlist_items, through: :playlists, source: :items
  has_many :memory_items, through: :memories, source: :items
end

然后,您当然使用user.playlist_itemsuser.memory_items

最新更新