Reputation: 199
DB is PostgreSQL. How do you append a value for all records to a column that has an array data type?
For example:
# migration_file.rb
def change
add_column :users, :tags, :string, array: true, default: []
end
How do I append the same value to the tags
attributes to all User records? I want to do something like:
User.update_all(tags << "some_tag")
Upvotes: 2
Views: 3570
Reputation: 434615
You can pass an SQL snippet to update_all
so you can use all the usual PostgreSQL array operators. For example:
User.update_all(['tags = tags || ?::text', 'some_tag'])
or without the ||
ambiguity (and corresponding cast):
User.update_all(['tags = array_append(tags, ?)', 'some_tag'])
User.update_all(['tags = tags || array[?]', 'some_tag'])
Note that you'd be passing update_all
an array in this case, you need to do that to convince AR that you want 'some_tag'
to fill in the placeholder rather than be the WHERE clause.
Upvotes: 5