繁体   English   中英

如何为活动记录枚举指定默认值?

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

给定以下具有enum列的ActiveRecord模型:

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

保存到数据库之前,如何设置role列的默认值。

例如:

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

或者如果你愿意的话

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

请注意,我们使用|| =来防止在使用User.new(some_params)初始化期间传入的任何内容的after_initialize clobbering

您可以将其设置为:默认为迁移文件中的“正常”。

小小的好例子: LINK

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

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

您可以使用此回调,before_save

class User < ActiveRecord::Base
     before_save :default_values

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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