I\'m trying to find the best way to set default values for objects in Rails.
The best I can think of is to set the default value in the new
method in
For boolean fields in Rails 3.2.6 at least, this will work in your migration.
def change
add_column :users, :eula_accepted, :boolean, default: false
end
Putting a 1
or 0
for a default will not work here, since it is a boolean field. It must be a true
or false
value.
Generate a migration and use change_column_default
, is succinct and reversible:
class SetDefaultAgeInPeople < ActiveRecord::Migration[5.2]
def change
change_column_default :people, :age, { from: nil, to: 0 }
end
end
If you are referring to ActiveRecord objects, you have (more than) two ways of doing this:
E.G.
class AddSsl < ActiveRecord::Migration
def self.up
add_column :accounts, :ssl_enabled, :boolean, :default => true
end
def self.down
remove_column :accounts, :ssl_enabled
end
end
More info here: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
E.G. before_validation_on_create
More info here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M002147
A potentially even better/cleaner potential way than the answers proposed is to overwrite the accessor, like this:
def status
self['name_of_var'] || 'desired_default_value'
end
See "Overwriting default accessors" in the ActiveRecord::Base documentation and more from StackOverflow on using self.
The suggestion to override new/initialize is probably incomplete. Rails will (frequently) call allocate for ActiveRecord objects, and calls to allocate won't result in calls to initialize.
If you're talking about ActiveRecord objects, take a look at overriding after_initialize.
These blog posts (not mine) are useful:
Default values Default constructors not called
[Edit: SFEley points out that Rails actually does look at the default in the database when it instantiates a new object in memory - I hadn't realized that.]
You can also try change_column_default
in your migrations (tested in Rails 3.2.8):
class SetDefault < ActiveRecord::Migration
def up
# Set default value
change_column_default :people, :last_name, "Smith"
end
def down
# Remove default
change_column_default :people, :last_name, nil
end
end
change_column_default Rails API docs