How to set default values in your model
Published over 4 years ago
In lights of recent discussion at rails core mailing list – I’m posting a code snippet showing how to set default values for your model without possibly screwing up.
class Item < ActiveRecord::Base def initialize_with_defaults(attrs = nil, &block) initialize_without_defaults(attrs) do setter = lambda { |key, value| self.send("#{key.to_s}=", value) unless !attrs.nil? && attrs.keys.map(&:to_s).include?(key.to_s) } setter.call('scheduler_type', 'hotseat') yield self if block_given? end end alias_method_chain :initialize, :defaults end
This will work even when you supply a block to Model.new – and it’s helpful in cases where you want to override default values.