This seems like a typical problem, but it is difficult to search for.
I want to select projects that a user owns via a has_many
and projects that a user is associated to via a has_many through
.
Consider the following models:
class User < ActiveRecord::Base
has_many :projects,
inverse_of: :owner
has_many :project_associations,
class_name: 'ProjectUser',
inverse_of: :user
has_many :associated_projects,
through: :project_associations,
source: :project
end
class Project < ActiveRecord::Base
belongs_to :owner,
class_name: 'User',
foreign_key: :owner_id,
inverse_of: :projects
has_many :user_associations,
class_name: 'ProjectUser',
inverse_of: :project
has_many :associated_users,
through: :user_associations,
source: :user
end
class ProjectUser < ActiveRecord::Base
belongs_to :project,
inverse_of: :user_associations
belongs_to :user,
inverse_of: :project_associations
end
It is trivial to do this with multiple queries:
user = User.find(1)
all_projects = user.projects + user.associated_projects
But I suspect it could be optimised using Arel into a single query.
Edit:
My first attempt at a solution using the find_by_sql
method is:
Project.find_by_sql([
'SELECT "projects".* FROM "projects" ' \
'INNER JOIN "project_users" ' \
'ON "projects"."id" = "project_users"."project_id" ' \
'WHERE "project_users"."user_id" = :user_id ' \
'OR "projects"."owner_id" = :user_id',
{ user_id: 1 }
])
This produces the result I am expecting, but I would like to avoid using find_by_sql
and instead let Arel build the SQL.