1

I have column_1(string) and i created column_2(string) and seriallized column_2 as array

class Model < ActiveRecord::Base
  serialize :column_2, Array
...

And i need to update column_2 with column_1 values, like this:

Model.update_all('column_2 = column_1')

But because i use serrialize as array for column_2, i need to save all values(strings) from column_1 as array

UPD. I tried .update_all('column_2 = (array[column_1]), but in this case, anyway when i call column_2 i get it as string:

"{\"value\"}"

1 Answer 1

1

Yes, it is possible using below query Use array_to_json to convert to array correctly

Model.update_all("column_2 = (array_to_json(array[column_1]))")

Incorrect: - I am not sure if directly using the SQL to convert the column data would work here. Rails has inbuilt serialize method that converts the data before pushing to sql. So the conversion of string to array is not possible at the sql level. You would need to resort to iterate over the records and update each record like below:-

model_instance.update('column_2 = ?', [column_1])
Sign up to request clarification or add additional context in comments.

1 Comment

I tested and was able to store the column as array using Model.update_all("column_2 = (array_to_json(array[column_1]))")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.