activerecord – 使用Rails更新附加到Postgresql中的文本列

在此预先感谢您提供任何帮助.

我在rails中有一个包含postgresql文本列的模型.

我想将(即mycolumn = mycolumn || newdata)数据附加到现有列.我想生成的sql看起来像:

update MyOjbs set mycolumn = mycolumn || newdata where id = 12;

我宁愿不选择数据,更新属性,然后将新数据写回数据库.文本列可能会变得相对较大,如果我不需要,我宁愿不读取该数据.

我不想这样做:

@myinstvar = MyObj.select(:mycolumn).find(12)
newdata = @myinstvar.mycolumn.to_s + newdata
@myinstvar.update_attribute(:mycolumn, newdata)

我是否需要执行原始sql事务才能完成此操作?

最佳答案 我认为你可以使用arel gem直接编写你的查询来解决这个问题,这已经提供了rails.

鉴于您有这些值:

column_id = 12
newdata = "a custom string"

你可以这样更新表:

# Initialize the Table and UpdateManager objects
table = MyOjbs.arel_table
update_manager = Arel::UpdateManager.new Arel::Table.engine
update_manager.table(table)

# Compose the concat() function
concat = Arel::Nodes::NamedFunction.new 'concat', [table[:mycolumn], new_data]
concat_sql = Arel::Nodes::SqlLiteral.new concat.to_sql

# Set up the update manager
update_manager.set(
  [[table[:mycolumn], concat_sql]]
).where(
  table[:id].eq(column_id)
)

# Execute the update
ActiveRecord::Base.connection.execute update_manager.to_sql

这将生成一个像这样的SQL字符串:

UPDATE "MyObjs" SET "mycolumn" = concat("MyObjs"."mycolumn", 'a custom string') WHERE "MyObjs"."id" = 12"
点赞