dimanche 16 avril 2017

get object using has many through with polymorphic association

I am using rails 5.

Here I am using has many through with polymorphic

Tables are

categories, category_items, albums

Models are

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

app/model/category.rb

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

app/model/category_item.rb

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

I am able to get categories of a specific album through association. but now I need to get albums of a specific category.

Please find the solution and make sure don't use method. association should be clean and simple

Many Thanks in Advance

Aucun commentaire:

Enregistrer un commentaire