更新 Rails 中的记录后返回

Nic*_*aru 5 postgresql activerecord ruby-on-rails arel

如何在 activerecord 中进行此查询:

UPDATE table_name SET column = 'value' WHERE id = 123 RETURNING other_column
Run Code Online (Sandbox Code Playgroud)

我试过了,update_all但它返回更改记录的数量,update_atributes返回真/假,并update返回整个对象。

在 Rails 中,它应该是这样的(伪代码):

other_column = TableName.where(:id => 123).update_attributes(:column => 'value').returning(:other_column)
puts other_column
Run Code Online (Sandbox Code Playgroud)

ush*_*sha 2

result_sets = Model.connection.execute("UPDATE table_name SET column = 'value' WHERE id = 123 RETURNING other_column")
result_sets.each do |result|
  p result[:other_column]
end
Run Code Online (Sandbox Code Playgroud)

如果你只想更新一条 id 为 123 的记录,为什么不能这样做呢?

   TableName.update(123, :column => 'value').other_column
Run Code Online (Sandbox Code Playgroud)