【问题标题】:get RETURNING after updating a record in rails更新rails中的记录后返回
【发布时间】:2014-03-12 17:11:28
【问题描述】:

如何在 activerecord 中进行查询:

UPDATE table_name SET column = 'value' WHERE id = 123 RETURNING other_column

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

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

other_column = TableName.where(:id => 123).update_attributes(:column => 'value').returning(:other_column)
puts other_column

【问题讨论】:

  • 请用您实现的代码详细说明您的问题。 (模型、控制器等)

标签: ruby-on-rails postgresql activerecord arel


【解决方案1】:
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

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

   TableName.update(123, :column => 'value').other_column

【讨论】:

  • 如果你要使用connection.execute,你必须小心引用/转义 SQL 中的值。
  • connection.execute 将绕过 rails 验证,update 将生成 2 个查询:selectupdate。我只需要一个查询。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 2015-01-01
  • 1970-01-01
  • 2017-05-27
  • 1970-01-01
  • 2011-01-13
  • 1970-01-01
相关资源
最近更新 更多