Rails 回形针:更新与 update_attributes [英] Rails Paperclip: update vs. update_attributes

查看:33
本文介绍了Rails 回形针:更新与 update_attributes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试通过回形针 gem 为我的用户模型(在 avatar 属性下)上传图像时,我意识到一些很奇怪的事情.出于某种原因, User.update 和 @user.update_attributes 的行为不同.有谁知道为什么会这样?

I realized something quite strange when attempting to upload an image via the paperclip gem for my user model (under the avatar attribute). For some reason there User.update and @user.update_attributes behaves differently. Does anyone know why this is so?

#using @user.update_attributes(user_avatar_params)
def update_profile_pic
    @user = User.find(params[:id])
    @user.update_attributes(user_avatar_params)
    puts @user.avatar_file_name.nil? # prints false as expected
    respond_to do |format|
      format.html { redirect_to :back }
      format.js
    end
end

#using User.update(@user.id, user_avatar_params)
def update_profile_pic
    @user = User.find(params[:id])
    User.update(@user.id, user_avatar_params)
    puts @user.avatar_file_name.nil? # prints true although successfully saves
    respond_to do |format|
      format.html { redirect_to :back }
      format.js
    end
end

这是我在 user_controller.rb 中的强参数

And here is my strong params in the user_controller.rb

def user_avatar_params
  params.require(:user).permit(:avatar)
end

推荐答案

ActiveRecord.update 有一个可能会让你失望的行为:

ActiveRecord.update has a behavior that may be throwing you off:

如果验证通过,则更新一个对象(或多个对象)并将其保存到数据库中.无论对象是否成功保存到数据库,都会返回结果对象.http://apidock.com/rails/ActiveRecord/Base/update/class

Updates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not. http://apidock.com/rails/ActiveRecord/Base/update/class

但是 update_attributes 只会返回 false.

这两个都使用模型级别的验证,因此两者都应该平等地保存或不保存.但是,返回值会有所不同.

Both of these use Model-level validations and so both should save or not save equally. However, the return values will be different.

正如@RoaringStones 指出的,解决方案是使用

As @RoaringStones pointed out, the solution is to use

user = User.update(user.id, user_avatar_params)

这篇关于Rails 回形针:更新与 update_attributes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆