Ruby on rails ArgumentError:分配属性时,必须将哈希作为参数传递
我正在从Rails 4升级到4.2。我有一个用户控制器,看起来像这样: 用户_controller.rbRuby on rails ArgumentError:分配属性时,必须将哈希作为参数传递,ruby-on-rails,ruby,hash,Ruby On Rails,Ruby,Hash,我正在从Rails 4升级到4.2。我有一个用户控制器,看起来像这样: 用户_controller.rb 从这里,假设#assign_attributes替换了#attributes(这实际上是它的一个函数。我可以推断参数[:user]没有响应#stringify_键。但是为什么?怎么做?解决方法是什么?你的参数[:user]是ActionController::Parameters的一个实例,我想……所以您只需要切换: @user.attributes=params[:user] 到 @use
从这里,假设
#assign_attributes
替换了#attributes
(这实际上是它的一个函数。我可以推断参数[:user]
没有响应#stringify_键
。但是为什么?怎么做?解决方法是什么?你的参数[:user]
是ActionController::Parameters的一个实例,我想……所以您只需要切换:
@user.attributes=params[:user]
到
@user.attributes=user_params
您应该使用user_params
,但我希望出现禁止属性错误
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
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