Hi all,
I’ve tried searching for the answer to this and I can’t seem to find an answer, so I wonder If I’m going about this the right way?
I basically have 3 models, user, organization and membership. A user can create an organisation, and can also belong to organizations through memberships, so organizations owned by other users.
I would like to be able to get all organizations that a user has access to, regardless if they own it, or they have access via a membership.
Do I need to merge owned_organizations and organizations? Or is there a better way to do this?
class User < ActiveRecord::Base
has_many :memberships
has_many :owned_organizations, class_name: "Organization", foreign_key: :user_id
has_many :organizations,-> { uniq }, through: :memberships, source: :user
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :organisation
end
class Organization < ActiveRecord::Base
has_many :memberships
has_many :members,-> { uniq }, through: :memberships, class_name: 'User', source: :user
end
I know how to write this in SQL, I just need the correct way to do this in Rails
SELECT organizations.*
FROM organizations
LEFT JOIN memberships ON organizations."id" = memberships.organization_id
WHERE organizations.user_id = '123' OR memberships.user_id = '123'
Any advice would be great! Thanks