0

我使用的轨道有很多5.获取对象通过与多态关联

这里我使用有许多通过与多态

表是

categories, category_items, albums 

模型是

Category, CategoryItem, Album 

app/model/album.rb

class Album < ApplicationRecord 
    has_many :category_items, as: :category_itemable, dependent: :destroy 
    has_many :categories, through: :category_items 
end 

应用程序/模型/ category.rb

class Category < ApplicationRecord 
    has_many :category_items, dependent: :destroy 
end 

应用程序/模型/ category_item.rb

class CategoryItem < ApplicationRecord 
    belongs_to :category_itemable, polymorphic: true, optional: true 
    belongs_to :category, optional: true 
end 

我能够通过联想获得一个特定的专辑类别。但现在我需要获取特定类别的专辑。

请找到解决方案,并确保不要使用方法。协会应该是干净和简单

很多感谢

回答

2

你只需要在Category模型

class Category < ApplicationRecord 
    has_many :category_items, dependent: :destroy 
    has_many :albums, through: :category_items, source: :category_itemable, source_type: 'Album' 
end 

增加对album一个has_many协会,现在你就可以得到专辑的类别实例

+0

谢谢。这是工作 –