运行类似:
@users = User.find(:first, :select => "name, lastname, Salary") for @user in @users do @user.salary = 100000 @user.save end
在 Mysql 表中查找之后,用户没有更新。
运行类似:
@users = User.find(:first, :select => "name, lastname, Salary") for @user in @users do @user.salary = 100000 @user.save end
在 Mysql 表中查找之后,用户没有更新。
ActiveRecord doesn't know the object's id, in order to save the data. So include the id field in :select, like the example below:
@users = User.find(:first, :select => "id, name, lastname, salary")
John Ruby 是正确的,您需要在选择中包含对象的 id。
此外,您很少需要使用 :select 选项。您可以使用连接,或者如果选择整行存在真正的性能问题,但这并没有太多。
而且您真的不需要将所有这些变量设置为实例变量 (@)。循环中的@user 可以是本地变量。如果您确实需要所有用户为@users,您可以这样做:
@users = User.find(:all, :select => "id、name、lastname、salary") @users.each 做 |user| user.salary = 10000 用户保存 结尾
您可能还想查看 ActiveRecord 的 update_all 以进行简单更改。但请注意,这不会调用任何保存回调。
尝试使用 .update 或 .update_attributes 代替:它们是为编辑而设计的(而不是 .save,它用于创建新行)
使用 .save!如果保存失败也会抛出错误。
我意识到这是一个非常老的问题,但我相信正确的答案是 :select 返回的任何对象都是只读的。
请参阅 Rails 官方的 Active Record 查询指南,第 3.2 节:http:
//guides.rubyonrails.org/active_record_querying.html
奇怪的是,我没有在 API 中看到这一点。