升级旧Rails应用至4.2.10遇ActiveModel::ForbiddenAttributesError求助
解决Rails 4.2.10升级后的ActiveModel::ForbiddenAttributesError问题
嘿,这个问题太常见了!Rails 4.x开始强制使用**强参数(Strong Parameters)**来保护批量赋值安全,这就是你升级后碰到ActiveModel::ForbiddenAttributesError的根源——Rails 3.2里直接用params[:user]的写法在4+版本里被彻底禁用啦。
问题原因
Rails 3.2及之前版本是通过模型里的attr_accessible控制可批量赋值的属性,而Rails 4+把这个逻辑移到了控制器层,要求显式声明哪些参数允许被赋值,防止恶意用户提交额外参数修改敏感数据。
修复步骤
你需要修改UsersController里的create和update方法,同时新增一个私有方法定义允许的参数:
修改后的控制器代码
# POST /users.json def create @user = User.new(user_params) # 替换原有的params[:user] respond_to do |format| if @user.save # 保留你原有的成功响应逻辑 format.html { redirect_to @user, notice: 'User was successfully created.' } format.json { render :show, status: :created, location: @user } else # 保留原有的失败响应逻辑 format.html { render :new } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # PUT /users/1 # PUT /users/1.json def update @user = User.find(params[:id]) respond_to do |format| if @user.update_attributes(user_params) # 替换原有的params[:user] format.html { redirect_to @user, notice: 'User was successfully updated.' } format.json { render :show, status: :ok, location: @user } else # 保留原有的失败响应逻辑 format.html { render :edit } format.json { render json: @user.errors, status: :unprocessable_entity } end end end private # 定义强参数,指定允许赋值的用户属性 def user_params # 替换成你User模型实际需要的属性,比如sorcery常用的字段 params.require(:user).permit(:email, :password, :password_confirmation, :name, :username) end
关键注意事项
- 一定要把
permit()里的字段换成你实际业务中需要的用户属性,比如如果你的用户模型有name、phone等字段,都要一一列出来,否则这些参数会被Rails过滤掉,无法保存到数据库。 - 对于sorcery Gem来说,
email、password、password_confirmation这几个字段是核心,必须包含在permit列表里,确保注册和密码修改功能正常。
内容的提问来源于stack exchange,提问作者uberdave
相关产品推荐
相关产品推荐

