简体   繁体   中英

How do I specify a default value for an active record enum?

Given the following ActiveRecord model with an enum column:

class User < ActiveRecord::Base
  enum role: [:normal, :sales, :admin]
end

How do I set the default value for the role column before saving to the database.

For example:

user = User.new
puts user.role # Should print 'normal'
class User < ActiveRecord::Base
  enum role: [:normal, :sales, :admin]

  after_initialize do
    if self.new_record?
      self.role ||= :normal
    end
  end
end

or if you prefer

class User < ActiveRecord::Base
  enum role: [:normal, :sales, :admin]

  after_initialize :set_defaults

  private

  def set_defaults
    if self.new_record?
      self.role ||= :normal
    end
  end
end

Note that we use ||= to prevent the after_initialize clobbering anything passed in during initialization with User.new(some_params)

You can set it as :default to 'normal' in a migration file.

little good examples: LINK

class User < ActiveRecord::Base
  enum role: [:normal, :sales, :admin]

  #before_save {self.role ||= 'normal'}
  # or
  #before_create {self.role = 'normal'}
end

You can use this callback, before_save

class User < ActiveRecord::Base
     before_save :default_values

        def default_values
          self.role ||= "normal"
        end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM