mentalic
mentalic

Reputation: 996

Setting of default when using add_column (Rails)

Usually when using add_column in a migration we have to set the default value by using :default => 0 OR :default => '' (if we add a string)

Is it possible to change the default add_column behaviour so that each time we add a column, if we add an integer, float etc 0 is set as default and if we add a string '' is set as the default?

Upvotes: 0

Views: 467

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176402

Usually when using add_column in a migration we have to set the default value by using :default => 0 OR :default => '' (if we add a string)

As long as you don't set null: false, there is no requirement to add a default value.

The default is required only if you set null: false or if you want a default value to be set.

Moreover, the configuration also depends on the database. Some database engines, if you set null: false and you don't provide a default explicitly, will automatically use the default value for the specific data type which in general is

  • 0 for integers
  • empty string for strings
  • 0.0 for floats
  • false for boolean

Again, it depends on the database. At Rails level, there is no way to set a global default, nor to change the behavior of add_column (unless you override it... but that would be a bad decision).

Upvotes: 1

Related Questions