Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails reset single column

I am trying to implement a rake task that will run once a month to reset a single column. I would prefer to reset the column to its default value but I cannot find any methods to help me accomplish this. reset_column_information does not work

What is the most efficient way to reset a single column in active record?

like image 572
Kyle C Avatar asked Dec 05 '25 20:12

Kyle C


1 Answers

Base method #update_all does the update direct in the database, so it is very efficient. However it bypasses callbacks because the models aren't loaded: http://apidock.com/rails/ActiveRecord/Base/update_all/class

SomeModel.update_all("some_column = 4");  # sets all some_column attributes to 4

Resetting it to the default depends on how you are setting the default in the first place. If the default is calculated in the model, then you would have to select and instantiate all the records, which could be very slow. If it's defined in the database, maybe it would be possible but I think it would be database specific.

like image 155
Tim Peters Avatar answered Dec 08 '25 12:12

Tim Peters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!