rosa-build/app/models/relation.rb

43 lines
1.5 KiB
Ruby
Raw Normal View History

2012-01-30 20:39:34 +00:00
# -*- encoding : utf-8 -*-
class Relation < ActiveRecord::Base
belongs_to :target, :polymorphic => true
belongs_to :actor, :polymorphic => true
2011-10-23 22:39:44 +01:00
ROLES = %w[reader writer admin]
validates :role, :inclusion => {:in => ROLES}
2011-10-23 22:39:44 +01: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
scope :by_user_through_groups, lambda {|u| where("actor_type = 'User' AND actor_id = ? OR actor_type = 'Group' AND actor_id IN (?)", u.id, u.group_ids)}
2012-09-11 21:08:25 +01:00
scope :by_actor, lambda {|obj| where(:actor_id => obj.id, :actor_type => obj.class.to_s)}
scope :by_target, lambda {|tar| where(:target_id => tar.id, :target_type => tar.class.to_s)}
scope :by_role, lambda {|role| where(:role => role)}
2011-11-30 15:27:19 +00: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-09-11 21:08:25 +01:00
def self.remove_member(member_id, target)
user = User.find(member_id)
Relation.by_actor(user).by_target(target).each{|r| r.destroy}
end
# @param user_remove looks like {"9"=>["1"], "32"=>["1"]}
def self.remove_members(user_remove, target)
user_ids = user_remove ? user_remove.map{ |k, v| k if v.first == '1' }.compact : []
Relation.by_target(target).where(:actor_id => user_ids, :actor_type => 'User').
each{|r| r.destroy}
end
2011-11-30 15:27:19 +00:00
protected
def add_default_role
self.role = ROLES.first if role.nil? || role.empty?
end
end