Rails如何“更新”多列正确-(updated_at也应更新) [英] how rails "update" multiple columns correctly - (updated_at should be updated as well)

查看:88
本文介绍了Rails如何“更新”多列正确-(updated_at也应更新)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用rails activerecord正确更新多列。我想使用类似update之类的东西,基本上更新了update_at,但是我只是不能传递多列。我可以使用update_all,但不会使用当前时间戳更新update_at。

I am having trouble updating multiple columns properly with rails activerecords. I want to use something like update which basically gets updated_at updated, but i just cant pass multiple column. I could use update_all but it doesnt update updated_at with the current timestamp.

这是我尝试过的操作:

这不起作用:(仅收取payment_total,而其余则不支付)

this doesnt work: (only takes in payment_total but not the rest)

retval = @invoice.update(:payment_total => 20, 
                         :due_amount => 10, 
                         :data => clonedata.to_json)  

:data - this is actually a json field

输出:

nothing

这有效:

 retval = Invoice.where(:id => @invoice.id).update_all(:payment_total => 20, 
                                                     :due_amount => 10, 
                                                     :data => clonedata.to_json)

输出:(注意它不会更新 updated_at字段)

output: (notice it doesnt update the "updated_at" field)

SQL(1.1ms)更新发票 SET payment_total = '30 .00', due_amount = '86 .00', data ='{ name: Test}'在发票中。 id = 6

SQL (1.1ms) UPDATE "invoices" SET "payment_total" = '30.00', "due_amount" = '86.00', "data" = ‘{"name":"Test}' WHERE "invoices"."id" = 6

单个参数将起作用:

retval = @invoice.update(:payment_total => 20)

输出:

UPDATE "invoices" SET "due_amount" = $1, "updated_at" = $2 WHERE "invoices"."id" = 6
  [["due_amount", "86.0"], ["updated_at", "2014-05-18 03:48:49.718692"]]

现在我该怎么办使用类似的方法来更新多个列,而updated_at还可以更新当前时间戳吗?

now how do i use something similar to update multiple columns while updated_at also gets the current timestamp updated ?

推荐答案

当您提到要更新多列-我想这将是一条记录?

When you mention you want to update multiple columns - I presume this would be for a single record?

该行将更新集合响应(。其中返回集合而不是单个对象):

This line will update a collection response (.where returns a collection rather than single object):

retval = Invoice.where(:id => @invoice.id).update_all(:payment_total => 20, 
                                                     :due_amount => 10, 
                                                     :data => clonedata.to_json)






如果您正在寻找更新单个记录,我会使用更新方法,例如:


If you're looking to update a single record, I would use the update method like this:

@invoice = Invoice.update(params[id], payment_total: "20", due_amount: "10", data: clonedata.to_json)

这篇关于Rails如何“更新”多列正确-(updated_at也应更新)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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