[英]Rspec-rails 4 error: ActiveModel::ForbiddenAttributesError
I have an application running in rails 4.1
using mongoid
as the orm. 我有一个使用
mongoid
作为orm在rails 4.1
运行的应用程序。 I created a model called User
which has an attribute email
. 我创建了一个名为
User
的模型,该模型具有一个email
属性。 I am using RSpec
for tests. 我正在使用
RSpec
进行测试。 I created the following spec 我创建了以下规范
require 'spec_helper'
describe 'User' do
before(:each) do
@attr = {
user: {
email: "rahul@gmail.com"
}
}
end
it "should create a valid User instance" do
param = ActionController::Parameters.new(@attr)
param.require(:user).permit!
User.create!(param)
end
end
when I run the spec, I get the following error 运行规范时,出现以下错误
Failure/Error: User.create!(param) ActiveModel::ForbiddenAttributesError: ActiveModel::ForbiddenAttributesError 失败/错误:User.create!(param)ActiveModel :: ForbiddenAttributesError:ActiveModel :: ForbiddenAttributesError
I know this is related to strong parameters but couldn't figure out what I am doing wrong. 我知道这与强大的参数有关,但无法弄清楚我在做什么错。
From the fine manual : 从精美的手册中 :
require(key)
需要(钥匙)
[...] returns the parameter at the given
key
[...][...]返回给定
key
处的参数[...]
So saying param.require(:user)
does nothing at all to param
, it merely does an existence check and returns param[:user]
. 所以说
param.require(:user)
完全param.require(:user)
param
做任何事情,它只进行存在检查并返回 param[:user]
。
I think you want to say something more like this: 我想您想说的是更多这样的话:
param = ActionController::Parameters.new(@attr)
User.create!(param.require(:user).permit!)
That usage would match the usual: 该用法将与通常的匹配:
def some_controller_method
@user = User.create(user_param)
end
def user_param
param.require(:user).permit!
end
usage in controllers. 控制器中的用法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.