2
我正在從Rails 4升級到4.2。我有一個用戶控制器,它看起來是這樣的:ArgumentError:分配屬性時,必須將散列作爲參數傳遞
user_controller.rb
class UsersController < ApplicationController
def new
end
def edit
end
protected
def create_with_token
@user.attributes = params[:user]
@user.validate_password = true
if @user.save
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(
:email, :first_name, :last_name, :password, :more_attributes
)
end
end
我還沒有確定,如果這事做與strong_params。但據我所知params[:user]
返回一個散列。那麼爲什麼我會在@user.attributes = params[:user]
上獲得ArgumentError: When assigning attributes, you must pass a hash as an argument.
?
我檢查了rails code,發現:
def assign_attributes(new_attributes)
if !new_attributes.respond_to?(:stringify_keys)
raise ArgumentError, "When assigning attributes, you must pass a hash as an argument."
end
return if new_attributes.empty?
attributes = new_attributes.stringify_keys
_assign_attributes(sanitize_for_mass_assignment(attributes))
end
從這裏,假設#assign_attributes
更換#attributes
(它實際上是爲它的alias我可以推斷params[:user]
沒有響應#stringify_keys
但爲什麼怎麼樣的。? ?工作圍繞
你應該使用'user_params',但我期待一個'forbiddenAttributesError' –