【问题标题】:How do I specify a default value for an active record enum?如何为活动记录枚举指定默认值?
【发布时间】:2016-03-03 21:52:31
【问题描述】:

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

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

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

例如:

user = User.new
puts user.role # Should print 'normal'

【问题讨论】:

  • 在保存到数据库之前是否有特定的原因需要做?这可以在将记录保存到数据库期间完成吗?

标签: ruby-on-rails ruby


【解决方案1】:
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

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

【讨论】:

  • 使用角色初始化对象时会发生什么:User.new(role: 'sales')?
  • 该死的你是对的。 after_initialize 会踩下参数......所以我需要一个 ||= 来不覆盖它。更新我的答案。
【解决方案2】:

您可以在迁移文件中将其设置为 :default 为“正常”。

好例子:LINK

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

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

【讨论】:

    【解决方案3】:

    你可以使用这个回调,before_save

    class User < ActiveRecord::Base
         before_save :default_values
    
            def default_values
              self.role ||= "normal"
            end
    end
    

    【讨论】:

    • 使用您的代码user = User.new; user.role 将返回nil。
    • 为什么不尝试通过迁移将默认值添加到现有列。
    • 数据库中设置的默认值仅在保存模型之后应用。
    猜你喜欢
    • 2013-07-25
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 2022-11-06
    • 1970-01-01
    • 2020-12-26
    • 2011-10-27
    • 2011-10-14
    相关资源
    最近更新 更多