Note that there are some explanatory texts on larger screens.

plurals
  1. PORails 3 has_many :through + join table conditions / scoping
    primarykey
    data
    text
    <p>I'm working on an app that has the models <code>User</code> and <code>Project</code>, and <code>User</code> can be assigned to multiple <code>Project</code>s, via <code>ProjectUser</code>, with a role (e.g. Developer, Designer).</p> <pre><code>Project has_many :project_users has_many :users, :through =&gt; :project_users User has_many :project_users has_many :projects, :through =&gt; :project_users ProjectUser (user_id, project_id, role) belongs_to :user belongs_to :project </code></pre> <p>I can call <code>@project.users</code> and <code>@user.projects</code>, but since there are varying roles, I'd like to be a bit more specific with the relations. Ideally, I want to be able to do the following:</p> <pre><code>@project.developers # returns @project.users, but only where ProjectUser.role = 'Developer' @project.designers &lt;&lt; @user # creates a ProjectUser for @project, @user with role 'Designer' @user.development_projects # returns projects where @user is assigned as a 'Developer' @user.design_projects &lt;&lt; @project # creates a ProjectUser for @project, @user with role 'Designer' </code></pre> <p>I currently have the following code:</p> <pre><code>has_many :developers, :through =&gt; :project_users, :source =&gt; :user, :class_name =&gt; "User", :conditions =&gt; ['project_users.role = ?','Developer'] </code></pre> <p>But this only really does the fetching one-way, and doesn't give me much else - I can't build or assign or anything.</p> <p>I'm attempting some more complex logic which I think might work, but would appreciate some pointers:</p> <pre><code>has_many :developer_assignments, :source =&gt; :project_user, :conditions =&gt; { :role =&gt; 'Developer' } has_many :developers, :through =&gt; :developer_assignments # class_name? </code></pre> <p>Any suggestions? Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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