我试图设置对嵌套资源(专业)ex的访问权限。 " ... /公司/:ID /特产&#34 ;.访问不属于我的公司工作正常。但我无法获得我的专业。请帮助我,因为我花了4个小时搜索解决方案而没有任何结果。 我有以下内容:
CanCan 1.6.9
//routes.rb
resources :companies do
resources :specialties
end
// ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.super_admin?
can :open, :admin_pages
else
cannot :open, :admin_pages
end
can [:edit, :update, :destroy], Company do |company|
company.try(:admin) == user
end
can :manage, Specialty
end
end
// companies_controller.rb
class CompaniesController < ApplicationController
load_and_authorize_resource
def new
@company = current_user.build_company
end
def create
@company = current_user.build_company params[:company]
if @company.save
redirect_to root_path, notice: I18n.t('notices.company_successfully_created')
else
render :new
end
end
def edit
@company = Company.find params[:id]
end
def update
@company = current_user.company
if @company.update_attributes(params[:company])
redirect_to root_path, notice: I18n.t('notices.company_successfully_updated')
else
render action: 'edit'
end
end
end
// specialties_controller.rb
class SpecialtiesController < ApplicationController
load_and_authorize_resource :company
load_and_authorize_resource through: :company
before_filter :company, except: [:destroy]
def index
@specialties = @company.specialties
respond_to do |format|
format.json {
resource = params[:resource_type]=='user' ? User.new : Profile.new
render :json => {:success => true, :html => (render_to_string '_specialties_list.html.slim', :locals => {:resource => resource})}
}
format.html {}
end
end
def new
@specialty = @company.specialties.build
end
def create
@specialty = @company.specialties.build params[:specialty]
if @specialty.save
redirect_to company_specialties_path, notice: I18n.t('notices.specialty_successfully_created')
else
render :new
end
end
def show
@specialty = Specialty.find params[:id]
end
def edit
@specialty = Specialty.find params[:id]
end
def update
@specialty = Specialty.find params[:id]
if @specialty.update_attributes(params[:specialty])
redirect_to company_specialties_path, notice: I18n.t('notices.specialty_successfully_updated')
else
render action: 'edit'
end
end
def destroy
@specialty = Specialty.find(params[:id])
@specialty.destroy
redirect_to company_specialties_path
end
private
def company
@company = Company.find(params[:company_id])
end
end
答案 0 :(得分:0)
在你的异能文件中,你只给了同一家公司的公司管理员[:edit,:update,:destroy]访问权。
当他尝试访问专业控制器中的任何操作时,第一个load_and_authorize_call:公司将尝试阅读公司。在阅读公司后,它将通过公司找到专业,并检查用户是否有权对特定行动采取特定行动。
在这种情况下,用户拥有专业的所有权限,但没有公司的读取权限,所以问题
所以添加:读取权限或使用以下权限授予所有权限:管理公司的管理员。
can [:read, :edit, :update, :destroy], Company do |company|
company.try(:admin) == user
end