How to check group membership with ruby code?
Added by Taner Tas over 4 years ago
I'm trying to find a proper syntax of doing such thing below. I want to add each members of a specific group as watchers if one of members of the group creates an issue.
The code below just the idea of what I'm trying to do:
if User.current Group.find(id).member_of? {
(Group.find(id).users).each {
|user| self.add_watcher(user) unless watched_by?(user)
}
}
Replies (4)
RE: How to check group membership with ruby code? - Added by kumar abhinav over 4 years ago
Hi Taner,
Will this help?
group = Group.find(id) if User.current.is_or_belongs_to?(group) group.users.each {|user| self.add_watcher(user)} rescue ActiveRecord::RecordNotFound # handle_resuce end
check for unless watched_by?(user) not needed, there is DB constraint in place to prevent duplicate records.
RE: How to check group membership with ruby code? - Added by Taner Tas over 4 years ago
Hi Kumar,
Thank you very much. This is first time I got a response from redmine forum. And it is a good one!
Your code worked in "Redmine Custom Workflow" plugin except "rescue ActiveRecord::RecordNotFound" line. I had to comment it out.
This is the error:
syntax error, unexpected rescue, expecting end rescue ActiveRecord::RecordNotFound
This is the custom workflow script:
if subject.present? group = Group.find(21) if User.current.is_or_belongs_to?(group) group.users.each {|user| self.add_watcher(user)} rescue ActiveRecord::RecordNotFound # handle_resuce end end
RE: How to check group membership with ruby code? - Added by kumar abhinav over 4 years ago
Hi Taner,
You are welcome.
My mistake, the rescue should have been after the if end block.
You could also do:
group = Group.find(21) rescue nil if group && User.current.is_or_belongs_to?(group)
As find will raise an exception if group is not found, it should be handled.
RE: How to check group membership with ruby code? - Added by Taner Tas over 4 years ago
Thank you. It worked.
Final Custom Workflow script:
if subject.present? group = Group.find(21) rescue nil if group && User.current.is_or_belongs_to?(group) group.users.each {|user| self.add_watcher(user)} end end