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
In case you're dealing with a Model, you can use the Attriutes API in Rails 5+ http://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html#method-i-attribute
just add a migration with a proper column name and then in the model set it with:
class StoreListing < ActiveRecord::Base
attribute :country, :string, default: 'PT'
end
First of all you can't overload initialize(*args)
as it's not called in all cases.
Your best option is to put your defaults into your migration:
add_column :accounts, :max_users, :integer, :default => 10
Second best is to place defaults into your model but this will only work with attributes that are initially nil. You may have trouble as I did with boolean
columns:
def after_initialize
if new_record?
max_users ||= 10
end
end
You need the new_record?
so the defaults don't override values loaded from the datbase.
You need ||=
to stop Rails from overriding parameters passed into the initialize method.
You can override the constructor for the ActiveRecord model.
Like this:
def initialize(*args)
super(*args)
self.attribute_that_needs_default_value ||= default_value
self.attribute_that_needs_another_default_value ||= another_default_value
#ad nauseum
end
You could use the rails_default_value gem. eg:
class Foo < ActiveRecord::Base
# ...
default :bar => 'some default value'
# ...
end
https://github.com/keithrowell/rails_default_value
If you're talking about ActiveRecord objects, I use the 'attribute-defaults' gem.
Documentation & download: https://github.com/bsm/attribute-defaults