What's the easiest way to find the 'middle' association in has_many :through association?
What I mean is, I have 3 models:
class VoiceActor < ApplicationRecord
has_many :characters
has_many :shows, through: :characters
end
class Character < ApplicationRecord
has_and_belongs_to_many :shows
belongs_to :voice_actor, optional: true
end
class Show < ApplicationRecord
has_and_belongs_to_many :characters
has_many :voice_actors, through: :characters
def character(voice_actor_id)
self.characters.find_by(voice_actor_id: voice_actor_id)
end
end
What I want to is, on a view page for a voice actor to display all shows they appear in. and next to each of those shows, show what character is played by them
I did get it to work, but I'm unsure if my solution is ok? Seems bit heavy on the view still. What I currently do is I pass @voice_actor to the view and @shows (which is just @voice_actor.shows) and use the character method defined in my show model as seen above
and then do
Appears in:
<ul>
<% @shows.each do |show| %>
<li>
<%= link_to show.name, show %> as <%= link_to show.character(@voice_actor.id).name, show.character(@voice_actor.id) %>
</li>
<% end %>
</ul>
would you say that's an okay solution or is there a more elegant way about it? I'm especially worried that I might be doing some bad practice regarding logic in the view