Using Ruby on Rails 3.2.13 and Squeel I have the following models:
class Group < ActiveRecord::Base
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
has_and_belongs_to_many :groups
has_many :characters, :dependent => :destroy
end
class Character < ActiveRecord::Base
belongs_to :user
end
Characters have a boolean attribute :public
.
Within the Character model, I want to retrieve all characters that are visible to the current user, as determined by the following conditions:
- The character belongs to the current user OR
- The character is public OR
- The current user shares a group with the character's user
The result has to be an ActiveRecord::Relation
.
Matching the first two conditions is simple enough:
def self.own_or_public user_to_check
where{
(user_id == user_to_check.id) |
(public)
}
end
For the third condition the following query yields the correct results, but is probably not the best way to do it:
def self.shares_group_with user_to_check
user_groups = Group.joins{users}.where{users.id == user_to_check.id}
joins{user.groups}.
where{
user.groups.id.in(user_groups.select(id))
}.uniq
end
Furthermore, I cannot find a way to concatenate the two results yielding an ActiveRecord::Relation
containing the results from both queries (merge
yields elements that match both queries, and +
returns an Array
instead of an ActiveRecord::Relation
).
Any help on how to handle this in one single Squeel query is much appreciated.