How to set default values in Rails?

后端 未结 17 1392
醉话见心
醉话见心 2020-11-28 04:39

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

17条回答
  •  星月不相逢
    2020-11-28 04:46

    I needed to set a default just as if it was specified as default column value in DB. So it behaves like this

    a = Item.new
    a.published_at # => my default value
    
    a = Item.new(:published_at => nil)
    a.published_at # => nil
    

    Because after_initialize callback is called after setting attributes from arguments, there was no way to know if the attribute is nil because it was never set or because it was intentionally set as nil. So I had to poke inside a bit and came with this simple solution.

    class Item < ActiveRecord::Base
      def self.column_defaults
        super.merge('published_at' => Time.now)
      end
    end
    

    Works great for me. (Rails 3.2.x)

提交回复
热议问题