rails中模型的默认值

Den*_*aev 13 ruby activerecord ruby-on-rails rails-activerecord

在迁移或回调中设置默认值是否更好?在迁移中很难删除(或设置另一个)默认值,但在模型中又需要一段代码

Sha*_*med 27

定义迁移中的默认值也有一些缺点.你打电话时这不起作用Model.new.

我更喜欢写after_initialize回调,它允许我设置默认属性:

class Model < ActiveRecord::Base
  after_initialize :set_defaults, unless: :persisted?
  # The set_defaults will only work if the object is new

  def set_defaults
    self.attribute  ||= 'some value'
    self.bool_field = true if self.bool_field.nil?
  end
end 
Run Code Online (Sandbox Code Playgroud)

  • `before_create` 只会在 DB 行中模型的生命周期内触发一次。每次更改数据库中的模型时,`before_update` 都会启动。 (2认同)

w_h*_*ile 15

在Rails 5中,属性API允许指定默认值.语法很简单,允许您在不迁移的情况下更改默认值.

# db/schema.rb
create_table :store_listings, force: true do |t|
  t.string :my_string, default: "original default"
end

# app/models/store_listing.rb
class StoreListing < ActiveRecord::Base
  attribute :my_string, :string, default: "new default"
end
Run Code Online (Sandbox Code Playgroud)