Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix member association filtering #48

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 28 additions & 17 deletions lib/groupify/adapter/active_record/group.rb
Original file line number Diff line number Diff line change
Expand Up @@ -145,23 +145,7 @@ def associate_member_class(member_klass)

def define_member_association(member_klass, association_name = nil)
association_name ||= member_klass.model_name.plural.to_sym
source_type = member_klass.base_class

if ActiveSupport::VERSION::MAJOR > 3
has_many association_name,
->{ uniq },
through: :group_memberships_as_group,
source: :member,
source_type: source_type,
extend: MemberAssociationExtensions
else
has_many association_name,
uniq: true,
through: :group_memberships_as_group,
source: :member,
source_type: source_type,
extend: MemberAssociationExtensions
end
has_many association_name, *association_options(member_klass)

define_method(association_name) do |*args|
opts = args.extract_options!
Expand All @@ -173,6 +157,33 @@ def define_member_association(member_klass, association_name = nil)
end
end
end

def association_options(member_klass)
source_type = member_klass.base_class
using_sti = (member_klass.base_class != member_klass)

base_options = {
through: :group_memberships_as_group,
source: :member,
source_type: source_type,
extend: MemberAssociationExtensions
}

if ActiveSupport::VERSION::MAJOR > 3
filter = using_sti ? -> { uniq.where("#{member_klass.table_name}.type = ?", member_klass.name.to_s) } : -> { uniq }

[
filter,
base_options
]
else
options = base_options.merge(uniq: true)
if using_sti
options.merge!(conditions: ["#{member_klass.table_name}.type = ?", member_klass.name.to_s])
end
[options]
end
end
end
end
end
Expand Down
9 changes: 9 additions & 0 deletions spec/active_record_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,15 @@ class ProjectMember < ActiveRecord::Base
expect(group.namespaced_members).to include(namespaced_member)
end

it "adds a model using STI to a group" do
manager = Manager.create!
user = User.create!
organization = Organization.create!
organization.add(manager, user)
expect(organization.users).to match_array [user, manager]
expect(organization.managers).to match_array [manager]
end

it "adds multiple members to a group" do
group.add(user, widget)
expect(group.users).to include(user)
Expand Down