Skip to content

Instantly share code, notes, and snippets.

@ansonhoyt ansonhoyt/ability.rb
Last active Dec 16, 2015

Embed
What would you like to do?
Authorizing polymorphic association with CanCan 1.6.9
class Ability
include CanCan::Ability
def initialize(user, session=nil)
@user = user
@session = session
@user ? user_rules : public_rules
end
def user_rules
can :update, Building, coach_id: @user.id
can :manage, Assignment do |assignment|
self.can? :update, assignment.assignable
end
end
end
class Assignment < ActiveRecord::Base
belongs_to :assignable, polymorphic: true
belongs_to :user
end
class AssignmentsController < ApplicationController
before_filter :load_assignments
authorize_resource
private
def load_assignable
if params[:program_id]
@assignable = @program = Program.find(params[:program_id])
elsif params[:building_id]
@assignable = @building = Building.find(params[:building_id])
elsif params[:classroom_id]
@assignable = @classroom = Classroom.find(params[:classroom_id])
end
end
def load_assignments
load_assignable
if @assignable
@assignments = @assignable.assignments
elsif params[:user_id]
@user = User.find(params[:user_id])
@assignments = @user.assignments
else
@assignments = Assignment.all.select {|a| can? :read, a}
end
end
end
class Building < ActiveRecord::Base
belongs_to :coach, class_name: "User"
has_many :assignments, as: :assignable, dependent: :destroy
end
class Program < ActiveRecord::Base
has_many :assignments, as: :assignable, dependent: :destroy
has_many :buildings
belongs_to :coach, class_name: "User"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.