How to set default values in Rails?

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

    If you are referring to ActiveRecord objects, you have (more than) two ways of doing this:

    1. Use a :default parameter in the DB

    E.G.

    class AddSsl < ActiveRecord::Migration
      def self.up
        add_column :accounts, :ssl_enabled, :boolean, :default => true
      end
    
      def self.down
        remove_column :accounts, :ssl_enabled
      end
    end
    

    More info here: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

    2. Use a callback

    E.G. before_validation_on_create

    More info here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M002147

提交回复
热议问题