1

我目前在使用最新版本的 CanCan 时遇到问题。似乎 gem 不会加载具有复数名称的单例资源。

class Preferences < ActiveRecord::Base
  self.table_name = 'preferences'
  belongs_to :user
end

class User < ActiveRecord::Base
  has_one :preferences
end

#controller
class PreferencesController < ApplicationController
  before_filter :authenticate_user! #from Devise

  load_and_authorize_resource :singleton => true,
                              :through => :current_user,
                              :through_association => :preferences,
                              :parent => false
end

#ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    can [:read, :update], Preferences, :user_id => user.id
  end
end

当我运行控制器规范时,我不断收到这样的错误:

Failures:

 1) PreferencesController GET #show should return http success
     Failure/Error: get :show
     NameError:
       uninitialized constant Preference
     # ./spec/controllers/preferences_controller_spec.rb:10:in `block (3 levels) in <top (required)>'

似乎无论load_resource我尝试哪种参数组合,如果不恢复手动加载资源,我都无法让我的规范再次通过,如下所示:

class PreferencesController < ApplicationController
  before_filter :authenticate_user!

  def show
    @preferences = current_user.preferences
    authorize! :read, @preferences
  end
end

load_and_authorize_resource我需要使用一些神奇的参数组合吗?我在另一个单例控制器中使用相同的配置,其中资源属于正常的 Rails 约定(即用户 has_one :profile),所以我知道这在正常情况下已经有效。

4

0 回答 0