trying ruby on rails fiddling around making small application. far rails way. have model administration has manager , organisation.
i want make sure - using validations - manager assigned adminisration associated organisation administrator belongs to.
i have working validation, gut-feeling says it's expensive on queries.
class administration < activerecord::base belongs_to :organisation belongs_to :manager, :class_name => "user", :foreign_key => 'manager_id' validates :code, numericality: true validates :manager_id, :presence => true validates :organisation_id, :presence => true validates :code, uniqueness: { scope: :organisation_id, message: 'bb: code in use' } validate :manager_belongs_to_organisation def manager_belongs_to_organisation errors.add(:base, 'bb: manager not exist') unless organisation.find(self.organisation_id).users.include?(user.find(self.manager_id)) end end
any thoughts on matter?
one way work around issue assign manager administration
. organization_id
automatically inserted using before_save
callback:
class administration ... before_save :update_organization_id ... def update_organization_id self.organization_id = self.manager.organization_id end end
Comments
Post a Comment