Rails: MassAssignmentSecurity::Error

折月煮酒 提交于 2019-12-12 10:08:17

问题


Following the ruby on rails guide developer can't mass-assign protected fields but don't get exception trying to do it, right? But in my case mass-assignment different params through new method in rails application:

@edition = Edition.new params[:edition]

raise following exception:

ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: price

Why? Did I understand something incorrectly? Is it a way not to get the mass-assignment exception? It's not convenient to delete protected attributes from hashes before assignments i think.

Update: Edition model:

class Edition < ActiveRecord::Base
  attr_accessible :title, :description
  attr_protected :price
end

params[:edition].inspect:

{"title"=>"t", "description"=>"d", "price"=>"123"}

回答1:


You are attempting to assign protected attribute price in mass assignment by putting

@edition = Edition.new params[:edition]

That is a mass assignment of variables and in params[:edition] according to your edit, there is the variable price which according to your code cannot be mass assigned.

To fix this you either have to remove the protection on price which I do not think you would want to do or mass-assign only the unprotected variables with new and then assign the protected variable. SO:

    @edition = Edition.new params[:edition].except("price")
    @edition.price = params[:edition]['price']

OR @edition = Edition.new params[:edition], :without_protection => true

EDIT: news.ycombinator.com/item?id=3780963 Rails 3.23 now makes the validation strict by default which raises that exception. The documentation is out of date.



来源:https://stackoverflow.com/questions/11014049/rails-massassignmentsecurityerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!