I want to remap values in my status column based on a hash.
For example if the status is a, change it to b.
How do I do this in Rails and optimize it so that it executes one db call that changes all values in the column?
I want to remap values in my status column based on a hash.
For example if the status is a, change it to b.
How do I do this in Rails and optimize it so that it executes one db call that changes all values in the column?
status_changes = { "a" => "b", "c" => "d" }
status_changes.each do |old, new|
# first arg is UPDATE, second arg is WHERE
SomeModel.update_all("status = #{new}", "status = #{old}")
end
If the hash is small compared to the table, you can do a SQL UPDATE ... WHERE ...
for each entry in the hash, wrapped into a transaction.
I did this instead, using heredocs for better readability:
status_mapping = {"Open" => 1345, "Closed" => 1346, "Pending" => 1347}
query = ActiveRecord::Base.connection()
query.execute <<-SQL.strip_heredoc
UPDATE table_1
SET status = CASE
WHEN status = #{status_mapping["Open"]} THEN 0
WHEN status = #{status_mapping["Closed"]} THEN 1
WHEN status = #{status_mapping["Pending"]} THEN 2
ELSE NULL
END;
SQL