I have actors who can have a role in a movie or in episodes of TV shows - my application treats these different and hence I have a model "Role" that is polymorphic. When I display an actor, I want to show two tables - one with all the movies they star in (sorted by movie title) and one with all the episodes they star in (again sorted by title). I am not sure how I access the "external" title field to do so. There must be something like @actor.roles.sort_by..... ?
Model: Actor
class Actor < ApplicationRecord
validates :first_name, presence: true
validates :first_name, uniqueness: { scope: :last_name }
has_many :roles, dependent: :destroy
has_many :movies, through: :roles, :source => 'castable', :source_type => 'Movie'
has_many :episodes, through: :roles, :source => 'castable', :source_type => 'Episode'
...
Model: Role
class Role < ApplicationRecord
belongs_to :actor
belongs_to :castable, polymorphic: true
end
Model: Movie
class Movie < ApplicationRecord
validates :title, presence: true, uniqueness: true
has_many :roles, as: :castable, dependent: :destroy
has_many :actors, through: :roles
...
Model: Episode
class Episode < ApplicationRecord
has_many :roles, as: :castable, dependent: :destroy
has_many :actors, through: :roles
...
CodePudding user response:
I have found parts of the answer in this SO question. Not sure how elegant this is, but it works :)