2

I have a number of tables in which I set all fields to zero, except for a few select ones (including foreign keys and some time values), on a weekly basis. At the moment, I'm using the update_all(field: value, ...) command, which works just fine. The only issue is that I have to list out each field I want to clear, and I often forget to add the field here when I change the table, which leads to errors.

Is there some way to have rails clear all fields in a table except for a specified few?

Thanks!

Ilya Lavrov
  • 2,810
  • 3
  • 20
  • 37
Nathan Lauer
  • 381
  • 5
  • 18

1 Answers1

3

In Rails every model has method columns which returns list of columns. You may do something like this for every model:

columns = Entry.columns.map(&:name)
# => ["id", "dish_id", "name", "value"]
columns_to_update = columns - ["id"]
# => ["dish_id", "name", "value"]
columns_with_zero = columns_to_update.map { |c| [c, 0] }.to_h
# => {"dish_id"=>0, "name"=>0, "value"=>0}
Entry.update_all columns_with_zero
# UPDATE "entries" SET "dish_id" = 0, "name" = '0', "value" = 0
Ilya Lavrov
  • 2,810
  • 3
  • 20
  • 37