How to set default values in Rails?

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

    A potentially even better/cleaner potential way than the answers proposed is to overwrite the accessor, like this:

    def status
      self['name_of_var'] || 'desired_default_value'
    end
    

    See "Overwriting default accessors" in the ActiveRecord::Base documentation and more from StackOverflow on using self.

提交回复
热议问题