John
John

Reputation: 634

Get data through many to many relations

I have 3 tables:

User class

 User has_many :project_assignments
 User has_many :projects, through: :project_assignments

ProjectAssignment class

 ProjectAssignment  belongs_to :user
 ProjectAssignment  belongs_to :project_owner, class_name: 'User', foreign_key: 'user_creator_id' 
 ProjectAssignment  belongs_to :project

Project

has_many :project_assignments
has_many :users, through: :project_assignments

ProjectAssignment has the columns:

 project_id, user_id, creator_user_id

I want to get all the projects, for a user through creator_user_id

ex: current_user.created_projects

The query: ProjectAssignment.where(creator_user_id: current_user.id)

Can it be done when defining the relations in the models, the same as I did with projects but the foreign_key should be creator_user_id

Upvotes: 0

Views: 35

Answers (2)

John
John

Reputation: 634

In my case this was the correct solution:

 has_many :owned_project_assignments, class_name: "ProjectAssignment", foreign_key: 'user_creator_id'
 has_many :owned_projects, through: :owned_project_assignments, source: :project

Upvotes: 0

Max Williams
Max Williams

Reputation: 32933

I think you just need another couple of associations in User which leverage the creator_user_id field (as opposed to user.projects which will return the projects the user is a member of)

Try this -

#in User class
has_many :owned_project_assignments, :class_name => "ProjectAssignment", :as => :project_owner, :foreign_key => "user_creator_id"
has_many :owned_projects, :through => owned_project_assignments, :class_name => "Project", :source => :project, :as => :project_owner

the :source and :as options can be a bit tricksy, so this might not work, it's just off the top of my head...

Upvotes: 1

Related Questions