2011-10-13 16:55:03 +01:00
|
|
|
class Relation < ActiveRecord::Base
|
2014-03-11 07:39:25 +00:00
|
|
|
ROLES = %w[reader writer admin]
|
|
|
|
|
2014-01-21 04:51:49 +00:00
|
|
|
belongs_to :target, polymorphic: true
|
2014-02-17 21:32:47 +00:00
|
|
|
belongs_to :actor, polymorphic: true, touch: true
|
2011-10-23 22:39:44 +01:00
|
|
|
|
2014-01-21 04:51:49 +00:00
|
|
|
validates :role, inclusion: {in: ROLES}
|
2011-10-23 22:39:44 +01:00
|
|
|
|
2014-01-21 04:51:49 +00:00
|
|
|
# validate { errors.add(:actor, :taken) if Relation.where(actor_type: self.actor_type, actor_id: self.actor_id).present? }
|
2011-11-30 15:27:19 +00:00
|
|
|
before_validation :add_default_role
|
|
|
|
|
2014-03-11 07:39:25 +00:00
|
|
|
scope :by_user_through_groups, ->(u) {
|
|
|
|
where("actor_type = 'User' AND actor_id = ? OR actor_type = 'Group' AND actor_id IN (?)", u.id, u.group_ids)
|
|
|
|
}
|
|
|
|
scope :by_actor, ->(obj) { where(actor_id: obj.id, actor_type: obj.class.to_s) }
|
|
|
|
scope :by_target, ->(tar) { where(target_id: tar.id, target_type: tar.class.to_s) }
|
|
|
|
scope :by_role, ->(role) { where(role: role) }
|
2011-11-30 15:27:19 +00:00
|
|
|
|
2012-04-26 02:38:33 +01:00
|
|
|
def self.create_with_role(actor, target, role)
|
|
|
|
r = self.new
|
|
|
|
r.actor = actor
|
2011-11-30 15:27:19 +00:00
|
|
|
r.target = target
|
|
|
|
r.role = role
|
|
|
|
r.save
|
|
|
|
end
|
|
|
|
|
2012-10-17 14:46:16 +01:00
|
|
|
def self.add_member(member, target, role, relation = :relations)
|
2014-01-21 04:51:49 +00:00
|
|
|
if target.send(relation).exists?(actor_id: member.id, actor_type: member.class.to_s) || (target.respond_to?(:owner) && target.owner == member)
|
2012-09-12 14:07:34 +01:00
|
|
|
true
|
|
|
|
else
|
2014-01-21 04:51:49 +00:00
|
|
|
rel = target.send(relation).build(role: role)
|
2012-09-12 14:07:34 +01:00
|
|
|
rel.actor = member
|
|
|
|
rel.save
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2012-09-12 21:47:39 +01:00
|
|
|
def self.remove_member(member, target)
|
2012-10-17 14:46:16 +01:00
|
|
|
return false if target.respond_to?(:owner) && target.owner == member
|
2013-04-18 13:39:54 +01:00
|
|
|
res = Relation.by_actor(member).by_target(target).each{|r| r.destroy}
|
2013-04-17 21:53:17 +01:00
|
|
|
if member.is_a?(User) && ['Project', 'Group'].include?(target.class.name)
|
|
|
|
member.check_assigned_issues target
|
|
|
|
end
|
2013-04-18 13:39:54 +01:00
|
|
|
res
|
2012-09-11 21:08:25 +01:00
|
|
|
end
|
|
|
|
|
2011-11-30 15:27:19 +00:00
|
|
|
protected
|
2012-02-20 23:13:05 +00:00
|
|
|
|
|
|
|
def add_default_role
|
|
|
|
self.role = ROLES.first if role.nil? || role.empty?
|
|
|
|
end
|
2011-10-13 16:55:03 +01:00
|
|
|
end
|