Kyle C
Kyle C

Reputation: 4097

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?

Upvotes: 3

Views: 3705

Answers (2)

Oskar Holmkratz
Oskar Holmkratz

Reputation: 145

If you're hardcore you can also drop the column(s) in a migration and then recreate it/them. Sometimes this will be a lot faster. I wouldn't do it in a critical application automatically - but if you're fiddling with your own local machine and just want to test stuff quick, this can be effective.

Upvotes: 0

Tim Peters
Tim Peters

Reputation: 4144

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.

Upvotes: 7

Related Questions