【问题标题】:Rails + CanCan + Polymorphic Association not working as expectedRails + CanCan + 多态关联未按预期工作
【发布时间】:2012-01-30 21:56:29
【问题描述】:

我正在尝试让 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 操作对 user_areas 和 account_areas 都很有效,但是当我尝试转到区域的索引操作时,我收到以下错误:

NameError in AreasController#index

uninitialized constant Owner

有什么想法吗?非常感谢

【问题讨论】:

  • 你能粘贴你的控制器代码吗?
  • 抱歉有点疏忽...

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


【解决方案1】:

它认为你的班级叫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 associations 上的标题:https://github.com/ryanb/cancan/wiki/Nested-Resources

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多