Reputation: 271
I have a Team class that inherits from a Group class. Both Team and Groups have memberships through the same association. However, I need to run a method after a Team memberships is added but not a Group. I currently have something like this:
class Group < ActiveRecord::Base
has_many :memberships,
:class_name => 'Connection',
:foreign_key => 'connectable_id',
:as => :connectable,
:dependent => :destroy
end
class Team < Group
has_many :memberships,
:class_name => 'Connection',
:foreign_key => 'connectable_id',
:as => :connectable,
:dependent => :destroy,
:after_add => :membership_check
private
def membership_check(membership)
end
end
Is there some way to modify the inherited association in Team so that I don't have to redefine the entire thing but rather just add the :after_add hook it?
Any help would be appreciated.
Upvotes: 3
Views: 242
Reputation: 37357
Try this and let me know if it works. It should I think. Make sure that your membership_check
method is not private anymore.
class Group < ActiveRecord::Base
has_many :memberships,
:class_name => 'Connection',
:foreign_key => 'connectable_id',
:as => :connectable,
:dependent => :destroy,
:after_add => proc {|gr, dev| gr.membership_check(dev) if gr.respond_to? :membership_check}
end
class Team < Group
def membership_check(membership)
end
end
P.S. I'm not sure what you needed to pass into the membership_check argument, but the added developer seems to make sence.
P.P.S If you want to keep membership_check
private, you may use gr.send(:membership_check, dev) to bypass the visibility constraint. But I don't see why you should.
Upvotes: 1
Reputation: 7105
Have you tried just adding the :after_add
hook in only the subclass Team? It won't get called in Group since it's the superclass, right?
Upvotes: 0
Reputation: 19475
The clearest way I can see is to define add_company_membership
in the Group
class as an empty method, then override it in Team
to actually do what you want there. You then keep the :after_add
on Group and go from there.
Unfortunately it's not as clean as just being able to ignore any idea of :after_add in the Group class, which would be ideal.
Upvotes: 0