2014-02-05 12 views
4

此前感謝任何幫助。使用Rails更新追加到Postgresql中的文本列

我有一個包含postgresql文本列的rails模型。

我想追加(即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事務做到這一點?

+0

我認爲你將不得不使用'increment_counter' http://www.alfreddd.com/2011/01/atomic-increment-in-rails.html或'update_all' http://stackoverflow.c OM /問題/ 4698046 /導軌,如何做增量-的整數-場的選擇 - 實例對的一模型 – phoet

回答

2

我想你可以直接用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"