title: has_many :through, 3 way join
body: <p>I have a Play that has many CostumedActors. A CostumedActor is a join of Actors and Costumes which have a many to many relationship.</p>
  
  <p>This seems to be a pattern that should be quite common, but I'm not clear about the best way to do it in rails.</p>
  
  <p>I have currently set it up as a 3-way join association as follows:</p>
  
  <pre><code>class Play &lt; ActiveRecord::Base
    has_many :costumed_actors
    has_many :actors, :through =&gt; costumed_actors
    has_many :costumes,:through =&gt; costumed_actors
  end
  
  class CostumedActor &lt; ActiveRecord::Base
    belongs_to :play
    belongs_to :costume
    belongs_to :actor
  end
  
  class Costume &lt; ActiveRecord::Base
    has_many :actors, :through =&gt; costumed_actors
    has_many :plays, :through =&gt; costumed_actors
  end
  
  class Actor &lt; ActiveRecord::Base
    has_many :costumes, :through =&gt; costumed_actors
    has_many :plays, :through =&gt; costumed_actors
  end
  </code></pre>
  
  <p>Rails doesn't handle this perfectly.  If I want to see the actors or costumes in a play, no problem:</p>
  
  <pre><code>play.costumes
  play.actors  
  </code></pre>
  
  <p>But if I want to see which costume an actor wears, I can't do </p>
  
  <pre><code>play.actors.costumes
  </code></pre>
  
  <p>In this case the .costumes gives me all the costumes each actor wears, across all plays, not just the current one.</p>
  
  <p>I have to do something like:</p>
  
  <pre><code>play.costumed_actors.where(:actor =&gt; @actor).map {|x| x.costumes}
  </code></pre>
  
  <p>or more cleanly, by adding a helper method to the has_many :through association</p>
  
  <pre><code>class Play
    has_many :costumes, :through =&gt; costumed_actors do
      def for_actor(actor)
        where("costumed_actors.actor_id = ?", actor) if !actor.nil?
      end
    end
  end
  
  play.costumes.for_actor(@actor)
  </code></pre>
  
  <p>Also, adding associations doesn't work correctly.  I'd like to be able to do something like</p>
  
  <pre><code>Play.actors &lt;&lt; actor.with_costume(costume)
  </code></pre>
  
  <p>But I can't see how to phase an association helper method, or even if that approach is possible.</p>
  
  <p>Is this the best way to represent this scenario, and if so is this the best way to read/write the associated records?</p>