Reputation: 3602
Given a List
model with the following associations:
has_many :list_group_memberships, dependent: :destroy
has_many :groups, through: :list_group_memberships
has_many :users, -> { unscope(:order).uniq }, through: :groups, source: :users
Basically I need to return the following but as an ActiveRecord::Relation, not an array:
def users
super + [user]
end
Ideally, the users
relation would use an or
scope, but I can't work it out.
Upvotes: 0
Views: 34
Reputation: 3602
I managed to solve it using the active_record_union gem and the following:
def users
super.union(User.where(id: user_id))
end
EDIT: I changed my implementation to use the solution posted by @mysmallidea
Upvotes: 0
Reputation: 9692
You could do this without the union gem:
# app/models/list.rb
def users_with_current_user
# Assuming `users` is the has_many :users relation on the list
# and `user` is a belongs_to relation on this list...
User.where(id: users).or(User.where(id: user))
end
This will automatically create an INNER JOIN on the list_group_memberships table.
Upvotes: 1