Rails 3, ActiveRecord, Detecting changes in has_many association
I have the following associations
class User < ActiveRecord::base
has_many :memberships
end
What I would like to do is to detect in the users_contro开发者_StackOverflowller
update action that some memberships have been added or removed from the user.memberships
.
Any idea or suggestion on how to implement this?
Thanks for any help.
EDIT: My apologies if the question was not clear.
Users are linked together by a parent-child relationship. This relationship is implemented through memberships to a Family circle.
What I want is that when a child user joins a Classroom circle automagically the parent of the child also joins the same Classroom circle. In other words adding/removing memberships to a child user needs to be propagated to his parents users.
My apologies if the context was not very clear. So first some context clarification:
Users are linked together by a parent-child relationship. This relationship is implemented through memberships to a Family circle.
What I want is that when a child user joins a Classroom circle automagically the parent of the child also joins the same Classroom circle. In other words adding/removing memberships to a child user needs to be propagated to his parents users.
Now the solution:
The way I have solved this is by adding the after_save and before_destroy methods to the Membership model to check is the user is a child and in that case to create/destroy membership for the parents. There are several tricky edge-cases I had to solve but the code seems to be working fine.
A final note: my first idea was to somehow detect in the user controller that memberships have been added or removed and then check if the user was a child user....
I know I'm late to the party here, but for future travelers ActiveRecord exposes before_add
, after_add
, before_remove
, and after_remove
hooks for exactly these scenarios.
Added how? Since the last visit?
If so, then make a "read" boolean column that updates when you visit.
Otherwise, elaborate. :)
精彩评论