将属性的值重置为默认值

时间:2016-11-25 11:55:27

标签: ruby-on-rails activerecord

我想知道如何设置模型属性和可能的​​关联到它的默认值。

user = User.find_by(name: "Martin")
user.phone = 012345
user.save!
# some time later
user.phone = # set to default
user.save!

3 个答案:

答案 0 :(得分:1)

设置列默认值的选项很少:

  1. 在迁移中设置默认值(可选)
  2. before_*回拨
  3. 中设置默认值

    还原为默认列的值,您可以使用ActiveRecord::ConnectionAdapters::SchemaCache#columns_hash

    user.phone = user.class.columns_hash['phone'].default
    

答案 1 :(得分:1)

您已在迁移中设置默认值。

:default => 'your_default

答案 2 :(得分:0)

最好使用:

User.column_defaults["phone"]

代替:

User.columns_hash['phone'].default

因为columns_hash获得了在数据库级别定义的原始默认值,并且跳过了ActiveModel中设置的默认值。请参见以下示例:

class Order < ApplicationRecord
  enum status: %i[open closed]
  attribute :deliver_at, default: -> { Date.tomorrow }
end

Order.columns_hash['status'].default # => "0" ('0' if default value was defined in the database or 'nil' otherwise)
Order.columns_hash['deliver_at'].default # => NoMethodError (undefined method `default' for nil:NilClass) if it's a virtual attribute or 'nil' if the column exists in the database 

Order.column_defaults['status'] # => "open"
Order.column_defaults['deliver_at'] # => Wed, 06 May 2020