Rails + CanCan + Polymorphic Association无法按预期工作

时间:2012-01-30 21:56:29

标签: ruby-on-rails-3.1 cancan polymorphic-associations

我正在尝试使用cancan来处理多态关联,我已经阅读了文档和wiki并且无法使其工作...

我有以下型号:

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

并在控制器中:

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      

以及以下能力:

  can :manage, Area, :owner => { :memberships => { :user => { :id => user.id } } } # Accounts through Membership     
  can :manage, Area, :owner => { :id => user.id } # User

new和create actions对user_areas和account_areas都有用,但是当我尝试去区域的索引操作时,我得到以下错误:

NameError in AreasController#index

uninitialized constant Owner

有什么想法?非常感谢

1 个答案:

答案 0 :(得分:2)

它认为您的班级名为Owner,也许您可​​以尝试:

load_resource :user, :instance_name => :owner, :class=>'User'
load_resource :account, :instance_name => :owner, :class=>'Account'
load_and_authorize_resource :area, :through => :owner

如果不起作用,请查看此问题是否解决了您的问题:https://github.com/ryanb/cancan/issues/73

如果您使用的是1.3或更高版本,则根据故障单,您可以执行以下操作:

load_resource :user
load_resource :account
load_and_authorize_resource :area, :through => [:user, :account]

但在这种情况下,您的authorize_parent方法会发生如下变化:

def authorize_parent
  authorize! :manage, (@user||@account)
end    

有关详细文档,请参阅标题Polymorphic associationshttps://github.com/ryanb/cancan/wiki/Nested-Resources

让我知道是否适合您。干杯安迪;)