CanCan load_and_authorize_resource触发禁止的属性 [英] CanCan load_and_authorize_resource triggers Forbidden Attributes
问题描述
我有一个使用强参数的标准RESTful控制器。
I have a standard RESTful controller that uses strong parameters.
class UsersController < ApplicationController
respond_to :html, :js
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def edit
@user = User.find(params[:id])
end
def create
@user = User.new(safe_params)
if @user.save
redirect_to @user, notice: t('users.controller.create.success')
else
render :new
end
end
def update
@user = User.find(params[:id])
if @user.update_attributes(safe_params)
redirect_to @user, notice: t('users.controller.update.success')
else
render :edit
end
end
def destroy
@user = User.find(params[:id])
if current_user != @user
@user.destroy
else
flash[:error] = t('users.controller.destroy.prevent_self_destroy')
end
redirect_to users_url
end
private
def safe_params
safe_attributes =
[
:first_name,
:last_name,
:email,
:password,
:password_confirmation,
]
if current_user.is?(:admin)
safe_attributes += [:role_ids]
end
params.require(:user).permit(*safe_attributes)
end
end
在我的 config / initializers
中,我有文件 strong_parameters.rb
ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)
当我向CanCan的 load_and_authorize_resource $ c $添加简单调用时c>我得到
When I add a simple call to CanCan's load_and_authorize_resource
I get
1) UsersController POST create with invalid params re-renders the 'new' template
Failure/Error: post :create, user: @attr
ActiveModel::ForbiddenAttributes:
ActiveModel::ForbiddenAttributes
# ./spec/controllers/users_controller_spec.rb:128:in `block (4 levels) in <top (required)>'
其中测试中 @attr
的定义为
before(:each) do
@attr =
{
first_name: "John",
last_name: "Doe",
email: "user@example.com",
password: "foobar",
password_confirmation: "foobar"
}
end
在测试中,我已经正确设置了所有设置,可以登录用户并赋予他们必要的角色成为管理员,所以我知道不是那样。我不知道为什么这会触发ForbiddenAttributes。我敢肯定,这是我忽略了的简单事情。
In the tests I have it all setup properly to login the user and give them the necessary roles for being an administrator so I know it's not that. I don't know why this is causing ForbiddenAttributes to trigger. I'm sure it's something simple I've overlooked. Has anyone else encountered this problem and found a solution to it?
推荐答案
我相信这是因为CanCan将使用自己的getter方法如果不使用before_filter预先加载请求的资源。因此,您可以将其添加到控制器中,并且应该可以正常工作:
I believe this is because CanCan will use its own getter method for the requested resource if you don't pre-load it with a before_filter. So you could add this to the controller and it should work:
class UsersController < ApplicationController
before_filter :new_user, :only => [:new, :create]
load_and_authorize_resource
def new_user
@user = User.new(safe_params)
end
end
(然后对编辑/更新操作执行相同的操作。)
(And then do the same for the edit/update actions.)
这篇关于CanCan load_and_authorize_resource触发禁止的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!