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

2024-03-29

预先感谢您对此提供的任何帮助。

我有一个 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 事务来完成此操作吗?


我认为您可以使用直接编写查询来解决这个问题arelgem,已经提供了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"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Rails 更新附加到 Postgresql 中的文本列 的相关文章

随机推荐