使用Rails更新追加到PostgreSQL中的文本列 [英] Using Rails Update to Append to a Text Column in Postgresql

查看:190
本文介绍了使用Rails更新追加到PostgreSQL中的文本列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此先感谢在这一个任何帮助。

Thanks in advance for any help on this one.

我有一个铁轨模型,其中包括PostgreSQL的文本列。

I have a model in rails that includes a postgresql text column.

我要追加(即根据MyColumn =根据MyColumn || newdata )的数据到现有列。

I want to append (i.e. mycolumn = mycolumn || newdata) data to the existing column. The sql I want to generate would look like:

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

我宁愿不选择数据,更新属性,然后写入新的数据到数据库中。文本列可能增长比较大的,我宁愿不读取数据,如果我不需要。

I would rather not select the data, update the attribute and then write the new data back to the database. The text column could grow relatively large and I'd rather not read that data if I don't need to.

我不希望做到这一点:

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

我需要做一个原始的SQL事务做到这一点?

Do I need to do a raw sql transaction to accomplish this?

推荐答案

我想你可以解决这个问题直接写入使用 AREL 宝石您的查询,这已经具备轨道

I think you could solve this problem directly writing your query using the arel gem, that's already provided with rails.

既然你有这些值:

column_id = 12
newdata = "a custom string"

您可以更新表是这样的:

you can update the table this way:

# 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字符串:

This will generate a SQL string like this one:

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

这篇关于使用Rails更新追加到PostgreSQL中的文本列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆