CanCan和InheritedResources:通过URL中没有ID param的单例资源加载和授权资源

时间:2014-03-04 07:00:26

标签: ruby-on-rails singleton cancan nested-routes inherited-resources

我的用户可以定义自己的词汇表。

class User < ActiveRecord::Base
  has_many :vocabularies
end

class Vocabulary < ActiveRecord::Base
  belongs_to :user
end

路线:

resource :user do
  resources :vocabularies
end

现在我想使用CanCan通过CategoriesController中加载的用户资源加载和授权词汇资源,但我很不确定如何正确配置CanCan。

有一件事是我没有通过URL参数传递用户的ID,所以我必须以某种方式告诉CanCan如何加载用户。我的猜测是我可以做一个through: :current_user。因为它是一个单例资源,我想我必须通过singleton: true选项:

class VocabulariesController < ApplicationController
  inherit_resources
  belongs_to :current_user # Is this correct?
  load_and_authorize_resource through: :current_user, singleton: true
end

但是在尝试访问user/vocabularies时,我收到Couldn't find Vocabulary without an ID错误。并且user/vocabularies/new会为{`产生undefined method current_user ='。不知道问题出在哪里,是CanCan吗? InheritedResources? Misconfig?

0 个答案:

没有答案