How to set default values in Rails?

后端 未结 17 1399
醉话见心
醉话见心 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 05:05

    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.

提交回复
热议问题