How to set default values in Rails?

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

    i answered a similar question here.. a clean way to do this is using Rails attr_accessor_with_default

    class SOF
      attr_accessor_with_default :is_awesome,true
    end
    
    sof = SOF.new
    sof.is_awesome
    
    => true
    

    UPDATE

    attr_accessor_with_default has been deprecated in Rails 3.2.. you could do this instead with pure Ruby

    class SOF
      attr_writer :is_awesome
    
      def is_awesome
        @is_awesome ||= true
      end
    end
    
    sof = SOF.new
    sof.is_awesome
    
    #=> true
    

提交回复
热议问题