Rails 4中未定义的方法update_attributes [英] undefined method update_attributes in Rails 4

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

问题描述

我现在正在使用Rails 4 现在我想更新我的用户记录 我正在尝试使用此命令

i'm now using Rails 4 now i want to update my user record i'm trying to use this command

@user=User.update_attributes(:name=> params[:name], :user=> params[:username], :pass=> params[:password])
OR
@user=User.update_attributes(name: params[:name], user: params[:username], pass: params[:password])

但总是出现错误

undefined method `update_attributes' 

那么我如何更新我的用户 我也想问一问,它将更新我数据库中的所有用户吗?

so how i can update my user also i want to ask is it will update all the users in my DB ??

我认为我必须添加诸如where id=@user.id之类的条件,但是我不知道该如何在Rails中做到这一点!!!

i think i must add some condition such as where id=@user.id but i don't know how i can do that in rails !!!

推荐答案

update_attributes是实例方法,而不是类方法,因此首先需要在User类的实例上调用它.

update_attributes is an instance method not a class method, so first thing you need to call it on an instance of User class.

获取要更新的用户: 例如假设您要更新ID为1的用户

Get the user you want to update : e.g. Say you want to update a User with id 1

 @user = User.find_by(id: 1)
 now if you want to update the user's name and password, you can do

两个

 @user.update(name: "ABC", pass: "12345678")

 @user.update_attributes(name: "ABC", pass: "12345678")

在您的情况下相应地使用它.

Use it accordingly in your case.

有关更多参考,您可以参考 Ruby on Rails指南.

For more reference you can refer to Ruby on Rails Guides.

您可以使用update_all方法来更新所有记录. 这是一个类方法,因此您可以将其称为 以下代码将更新所有用户记录的名称并将其设置为"ABC" User.update_all(name:"ABC")

You can use update_all method for updating all records. It is a class method so you can call it as Following code will update name of all User records and set it to "ABC" User.update_all(name: "ABC")

这篇关于Rails 4中未定义的方法update_attributes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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