Ruby on rails rails中模型的默认值

Ruby on rails rails中模型的默认值,ruby-on-rails,ruby,activerecord,rails-activerecord,Ruby On Rails,Ruby,Activerecord,Rails Activerecord,在迁移或回调中设置默认值更好吗?在迁移中很难删除(或设置另一个)默认值,但在模型中,在迁移中定义默认值的一段代码也有一些缺点。当您仅调用Model.new时,这将不起作用 我更喜欢编写回调,它允许我设置默认属性: class Model < ActiveRecord::Base after_initialize :set_defaults, unless: :persisted? # The set_defaults will only work if the object is

在迁移或回调中设置默认值更好吗?在迁移中很难删除(或设置另一个)默认值,但在模型中,在迁移中定义默认值的一段代码也有一些缺点。当您仅调用
Model.new
时,这将不起作用

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

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 
类模型
一般来说,在后端,在模型和数据库中实施约束。这就像验证JS,而不是在后端验证(PHP、ROR等)。有人可以修改您的JS以通过验证,因为您没有在后端进行验证,您的站点可能会受到损害。因此,始终在两个方面进行验证,至少如果您的应用程序服务器遭到破坏,DB服务器可能会进行一些防御。

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

# 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
#db/schema.rb
创建表:存储列表,强制:true do | t|
t、 字符串:my_字符串,默认值:“原始默认值”
结束
#app/models/store_listing.rb
类StoreListing
依靠@w-hile答案——这是一个很好的答案,除非你有很多事情要做“设置”-

我厌倦了用一堆关于设置的专栏来污染我的模型,所以我写道


为什么不在创建之前
?然后您不需要检查
:persistend?
@WojciechBednarski,因为在创建之前
将覆盖现有值,如果对象已经有值,我们不想设置默认值。这就是为什么我们只在对象是新的且未持久化时才设置默认值的原因。
before\u create
将在DB row中的模型的生命周期中只触发一次<每次更改数据库中的模型时,更新前的代码将触发。@SharvyAhmed谢谢您,先生。我注意到您的答案正在从模型中验证。也可以直接从创建控制器设置值。您对这种方法有何看法?@SharvyAhmed但是在迁移中使用默认值确实适用于
模型。新的
值得注意的是,Rails属性API将允许
,一个空字符串,使模型保持原样。这很好。好的一点是它也接受proc!是否也需要将其添加到迁移中?
class User < ApplicationRecord

  include ::Setsy::DSL

  # each setting can be a hash, like posts_limit, or just a value
  DEFAULT_SETTINGS = {
    posts_limit: { value: 10 },
    favorite_color: 'blue'
  }.freeze

  setsy :settings, column: :settings_data, defaults: DEFAULT_SETTINGS do |conf|
    conf.reader :posts_limit_and_color do
      "posts limit is #{posts_limit} and color is #{favorite_color}"
    end
  end
end
user = User.first
user.settings # {posts_limit: 10, favorite_color: 'blue'}
user.settings.posts_limit # 10
user.settings.posts_limit.default? # true 
user.assign_attributes(settings_data: { posts_limit: 15, favorite_color: 'blue' })
user.settings.posts_limit.default? # false 
user.settings.posts_limit.default # 10