Note that there are some explanatory texts on larger screens.

plurals
  1. POSpecifying the foreign key in a has_many :through relationship
    primarykey
    data
    text
    <p>I have the following three models: User, Project, and Assignment.</p> <p>A User <code>has_many</code> Projects through an assignment. However, Assignment actually has <em>two</em> foreign keys that relate to a User: <code>user_id</code> (representing the user who was assigned the project) and <code>completer_id</code> (representing the user who completed the project).</p> <p>Often, <code>user_id</code> and <code>completer_id</code> will be the same (if the user who was assigned the project completes it). However, if another user completes it, user_id and completer_id will be different.</p> <p>In my User model, I have the following: </p> <pre><code>class User &lt; ActiveRecord::Base has_many :assignments has_many :incomplete_assignments, :class_name =&gt; 'Assignment', :conditions =&gt; 'completer_id IS NULL' has_many :completed_assignments, :class_name =&gt; 'Assignment', :foreign_key =&gt; 'completer_id' # this is the important one has_many :incomplete_projects, :through =&gt; :assignments, :source =&gt; :project, :conditions =&gt; 'completer_id IS NULL' end </code></pre> <p>I would like to make another association, called <code>:completed_projects</code>, which uses <code>completer_id</code> as the foreign key for the User in the <code>:through</code> model, rather than <code>:user_id</code>. Is it possible to do this?</p> <p>And, as an aside, I am aware of the <code>:foreign_key</code> option. However, this option is ignored when using <code>:through</code>, so I'd like to know if there's a way to do this without it.</p> <p>Finally, I should mention that I'm open to other designs, if it can't be done this way and someone can think of a better way. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload