How to set default values in Rails?

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

    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.]

提交回复
热议问题