gpt4 book ai didi

ruby-on-rails - rails "update"多列如何正确 - (updated_at 也应该更新)

转载 作者:行者123 更新时间:2023-12-03 16:20:45 25 4
gpt4 key购买 nike

我在使用 rails activerecords 正确更新多个列时遇到问题。我想使用类似 update 的东西,它基本上会更新 updated_at,但我不能传递多列。我可以使用 update_all 但它不会使用当前时间戳更新 updated_at。

这是我尝试过的:

这不起作用:(只接受 payment_total 但不接受其余部分)

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”字段)

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 也会更新当前时间戳?

最佳答案

当您提到您想要更新多列时 - 我猜这是针对单个记录?


此行将更新一个collection 响应(.where 返回一个collection 而不是单个object):

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

如果您想更新单个记录,我会 use the update method像这样:

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

关于ruby-on-rails - rails "update"多列如何正确 - (updated_at 也应该更新),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23718419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com