Question

I'm adding a multiplier column to one of my models, and it should have a default value of 1. I'm wondering if it's preferable to add the default value at the database layer or in a callback in my model. I'm leaning toward model in the name of database agnosticity (if that's a word, which I guess it's not). Am I right to do so?

Was it helpful?

Solution

Since you can declare the default in a Rails migration and migrations use database adapters, setting the default in a migration is sufficiently database agnostic for most purposes. E.g.:

class AddMultiplierColumn < ActiveRecord::Migration
  def change
    add_column :my_table, :multiplier, :float, default: 1.0
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top