Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

ruby on rails - ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes

If I try to execute the following code:

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

I obain the following error:

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A couple things:

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"})

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

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.

Here are more details:

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

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...