I am trying to get cancan to work with a polymorphic association, i have read through the docs and wiki and am not able to get it working…
I have the following models:
class User < ActiveRecord::Base
has_many :areas, :as => :owner, :dependent => :destroy
end
class Account < ActiveRecord::Base
has_many :areas, :as => :owner, :dependent => :destroy
end
class Area < ActiveRecord::Base
belongs_to :owner, :polymorphic => true
end
and in the controller:
class AreasController < ApplicationController
load_resource :user, :instance_name => :owner
load_resource :account, :instance_name => :owner
load_and_authorize_resource :area, :through => :owner
before_filter :authorize_parent
respond_to :html
def authorize_parent
authorize! :manage, @owner
end
def index
end
def show
@events = @area.events.page(params[:page]).per(5)
respond_with @area
end
def new
respond_with @area
end
def create
@area = @owner.areas.new(params[:area])
if @area.save
flash[:notice] = "Your new area has been created..."
end
respond_with @area
end
end
and the following abilities:
can :manage, Area, :owner => { :memberships => { :user => { :id => user.id } } } # Accounts through Membership
can :manage, Area, :owner => { :id => user.id } # User
the new and create actions work great for both user_areas and account_areas but when i try to go to the index action of areas i get the following error:
NameError in AreasController#index
uninitialized constant Owner
Any thoughts? many thanks
It considers that your class is called
Owner, maybe you can try like:If dont works, see if this issue solves your problem: https://github.com/ryanb/cancan/issues/73
Based on the ticket if you are using 1.3 or later version then you can do the following:
But in this case your
authorize_parentmethod changes like this:For detailed documentation please see the title
Polymorphic associationson : https://github.com/ryanb/cancan/wiki/Nested-ResourcesLet me know if works for you. Cheers Andy 😉