.sample 在种子中不起作用

.sample not working in seeds

变量var是一个boolean,不能为空。因此在我的模型文件中我有:

validates_inclusion_of :var, :in => [true, false]
validates :var, presence: true

在我的种子文件中我有:

title = "abc"
var = [true, false].sample
author.articles.create!( title: title,
                         var: var)

播种产生错误:

ActiveRecord::RecordInvalid: Validation failed: Var can't be blank

有没有人明白为什么要创建一个带有空白 var 的文章?

更新: 使用 debugger,我可以确认 var 的值为 1。

文章架构:

  create_table "articles", force: :cascade do |t|
    t.integer  "author_id"
    t.string   "title",          limit: 50,                null: false
    t.boolean  "var",                       default: true, null: false
    t.datetime "created_at",                               null: false
    t.datetime "updated_at",                               null: false
  end

should not be allowed to be blank

更好的方法是在数据库中设置一个 default 值。

这不仅会释放 Rails 处理能力,而且还会确保无论如何,该值 必须 存在,这是 boolean:

$ rails g migration AddDefaultToBool

# db/migrate/add_default_to_bool____________.rb
class AddDefaultToBool < ActiveRecord::Migration
   def change
      change_column :articles, :var, :boolean, default: false
   end
end

$ rake db:migrate

这样,如果该值不存在,您将始终拥有 boolean 作为 false。我知道这不是您要问的具体问题,但无论如何都会是一个更好的解决方案。


就您的验证而言,您需要使用较新的 validates shorthand:

#app/models/article.rb
class Article < ActiveRecord::Base
   validates :var, presence: true, inclusion: [:true, :false]
end

根据 this question 的评论,boolean 值不应该是 presence

Note that you cannot have the usual validation for the presence (validates :field, presence: true) for a boolean field (the field would not be valid for a false value).

But in both Rails 3 and 4, having validates :field, inclusion: [true, false] would test for inclusion in a list of values, with the side-effect to test for the field's presence (unless one of those values is nil of course). – Martin Carel Jul 14 at 19:38

...所以您应该能够使用以下内容:

#app/models/article.rb
class Article < ActiveRecord::Base
   validates :var, inclusion: [:true, :false]
end

Another good ref