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
1.2k views
in Technique[技术] by (71.8m points)

ruby on rails - Can't mass assign protected attributes

My features file looks at this:

Given there are the following users:
    | email              | password | admin |
    | admin@ticketee.com | password | true  |

And my user model doesn't declare the admin attribute as attr_accessible to prevent mass assignment. Accordingly, I've made changes to the user_steps.rb file to tackle this.

Given /^there are the following users:$/ do |table|
  table.hashes.each do |attributes|
   unconfirmed = attributes.delete("unconfirmed") == "true"
   @user = User.create!(attributes)
   @user.update_attribute("admin", attributes["admin"] == "true")
   @user.confirm! unless unconfirmed
 end
end

Now this is supposed to work according to the book - Rails3 in action. I checked the code on their online repo as well. Running this with cucumber gives the following error:

Can't mass-assign protected attributes: admin (ActiveModel::MassAssignmentSecurity::Error)
  ./features/step_definitions/user_steps.rb:4:in `block (2 levels) in <top (required)>'
  ./features/step_definitions/user_steps.rb:2:in `each'
  ./features/step_definitions/user_steps.rb:2:in `/^there are the following users:$/'
  features/creating_projects.feature:7:in `Given there are the following users:'

Any help would be greatly appreciated. I really cant figure what's wrong here.

Thanks a lot!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In the user model add:

attr_accessible :admin

Update:

The admin attribute can be mass assigned and any hacker can set it easily by sending it with the parameters.


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

...