Rails: Should I set default column value at the database level, or in the model?

StackOverflow https://stackoverflow.com/questions/22621166

  •  20-06-2023
  •  | 
  •  

سؤال

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?

هل كانت مفيدة؟

المحلول

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top