rosa-build/app/models/relation.rb

31 lines
1.1 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 :object, :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(:object, :taken) if Relation.where(:object_type => self.object_type, :object_id => self.object_id).present? }
2011-11-30 15:27:19 +00:00
before_validation :add_default_role
scope :by_user_through_groups, lambda {|u| where("object_type = 'User' AND object_id = ? OR object_type = 'Group' AND object_id IN (?)", u.id, u.group_ids)}
2011-10-23 22:39:44 +01:00
scope :by_object, lambda {|obj| {:conditions => ['object_id = ? AND object_type = ?', obj.id, obj.class.to_s]}}
scope :by_target, lambda {|tar| {:conditions => ['target_id = ? AND target_type = ?', tar.id, tar.class.to_s]}}
scope :by_role, lambda {|role| {:conditions => ['role = ?', role]}}
2011-11-30 15:27:19 +00:00
def self.create_with_role(object, target, role)
r = new
r.object = object
r.target = target
r.role = role
r.save
end
protected
def add_default_role
self.role = ROLES.first if role.nil? || role.empty?
end
end