ActiveModel::MassAssignmentSecurity::Error: 无法批量分配受保护的属性 [英] ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes

查看:39
本文介绍了ActiveModel::MassAssignmentSecurity::Error: 无法批量分配受保护的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试执行以下代码:

If I try to execute the following code:

hassle = rota.hassles.create(:sender => user1, :receiver => user2, :type => "sms")

我发现以下错误:

Failure/Error: hassle = rota.hassles.create(:sender => user1, :receiver => user2, :type => "sms")
 ActiveModel::MassAssignmentSecurity::Error:
   Can't mass-assign protected attributes: type

我不确定这意味着什么.我已将 :type 设为强制,所以如果我删除它,我会收到一个 sql 错误.

I am not sure what this means. I have made the :type to be compulsory, so if I do remove it, I get an sql error.

推荐答案

一些事情:

批量赋值通常意味着将属性传递到调用中,该调用创建一个对象作为属性散列的一部分.也就是说,您将散列中的一堆属性传递到创建新对象的调用中.例如:

Mass Assignment usually means passing attributes into the call that creates an object as part of an attributes hash. That is, you pass a bunch of attributes in a hash into the call that creates the new object. For example:

@user = User.create({:name => "My name", :user_type => "nice_user"})

但是,Rails 包含一些基本的安全规则,这意味着并非所有属性都可以默认分配这种方式.您必须事先指定哪些可以.你这样做:

However, Rails includes some basic security rules that mean not all attributes can be assigned that way by default. You have to specify which ones can beforehand. You do so like this:

class User < ActiveRecord::Base
  attr_accessible :name, :user_type
end

如果您没有指定属性为 attr_accessible,并且您将其传入以创建对象,则会收到您发布的错误.

If you don't specify an attribute is attr_accessible, and you pass it in to create the object, you get the error you posted.

以下是更多详细信息:

http://api.rubyonrails.org/v3.2.9/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html

另一种方法是在您第一次创建记录时设置一些属性,然后设置其他属性——就像这样:

The alternative is to set some of the attributes when you first create the record, and set others after -- like so:

# In this example `user_type` is not attr_accessible so it needs to be set specifically
@user = User.create({:name => "My name"})
@user.user_type = "nice_user"
@user.save

此外,如果您在使用列名 type 时遇到问题,因为 rails 感到困惑并认为您想使用单表继承 (STI),请查看此问题的答案查看如何绕过它:http://guides.rubyonrails.org/

In addition, if you're having issues with using the column name type because rails is getting confused and thinks you want to use Single Table Inheritance (STI), check the answer to this question to see how to get around it: http://guides.rubyonrails.org/

这篇关于ActiveModel::MassAssignmentSecurity::Error: 无法批量分配受保护的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆