2012-01-30 20:39:34 +00:00
|
|
|
# -*- encoding : utf-8 -*-
|
2011-10-13 16:55:03 +01:00
|
|
|
class Relation < ActiveRecord::Base
|
|
|
|
belongs_to :target, :polymorphic => true
|
2012-04-26 02:38:33 +01:00
|
|
|
belongs_to :actor, :polymorphic => true
|
2011-10-23 22:39:44 +01:00
|
|
|
|
2011-11-24 19:22:37 +00:00
|
|
|
ROLES = %w[reader writer admin]
|
2011-11-16 18:45:01 +00:00
|
|
|
validates :role, :inclusion => {:in => ROLES}
|
2011-10-23 22:39:44 +01:00
|
|
|
|
2012-04-26 02:38:33 +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
|
|
|
|
|
2012-04-26 02:38:33 +01:00
|
|
|
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)}
|
|
|
|
scope :by_actor, lambda {|obj| {:conditions => ['actor_id = ? AND actor_type = ?', obj.id, obj.class.to_s]}}
|
2011-10-23 22:39:44 +01:00
|
|
|
scope :by_target, lambda {|tar| {:conditions => ['target_id = ? AND target_type = ?', tar.id, tar.class.to_s]}}
|
2011-12-26 15:48:57 +00:00
|
|
|
scope :by_role, lambda {|role| {:conditions => ['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
|
|
|
|
|
|
|
|
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
|