【问题标题】:.sample returns nil when seeding Rails app.sample 在为 Rails 应用程序播种时返回 nil
【发布时间】:2015-10-10 23:30:50
【问题描述】:

我正在构建一个 Rails 应用程序,但遇到了一个非常奇怪的错误。代码[true false].sample 永远不应该返回空白。但是,有时在运行rake db:seed 时会这样做。

在我的应用程序中,我有一个具有存在验证的 Store 模型:

class Store < ActiveRecord::Base
  validates_presence_of :accepts_credit, :parking
end

我也像这样在 rspec 中运行测试(总是通过)

require 'rails_helper'

RSpec.describe Store, type: :model do 
  it { should validate_presence_of :accepts_credit }  
  it { should validate_presence_of :parking        }  
end

现在,在我的种子文件中,我有

Store.create(
  ...
  accepts_credit: [false, true].sample(1),
  parking:      %w[lots some none].sample(1),
  ... 
)

使用rake db:reset --trace 在终端中运行此程序,我收到未创建商店的错误。我通过运行Store.create! 而不是Store.create 对此进行了检查,这会导致终端显示错误。Validation failed: Accepts credit can't be blank

现在,我对 Rails 比较陌生,但我不明白为什么示例方法 .sample 会返回空白。根据文档:http://ruby-doc.org/core-2.2.0/Array.html#method-i-sample,sample 总是从数组中返回一个元素。

编辑

我也用.sample 代替了.sample(1)

我错过了什么? .blank 在做我认为的事情吗?

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    false.blank?true(即不是“存在”),因此如果您想保留 false 值,则需要重写验证。如果你想保护nil,你可以试试validates_inclusion_of :accepts_credit, in: [true, false]

    【讨论】:

    • 好的,这是有道理的,这是我的第一个直觉,但是 shoulda-matchers 文档说你不应该在布尔值上使用包含。这是文档的链接:github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/….
    • 再想一想,我想这回答了这个问题。您不应该验证布尔值的存在,因为 AR 会将它们输入。您的答案是在了解 AR 在做什么之后做出的。谢谢!
    • AR 将在从数据库中提取记录后对值进行类型转换,因此无论包含验证如何,Store.last.accepts_credit? 都将按预期工作。尽管如此,确保布尔字段中没有 NULL 值可能很重要,因为像 Store.where(accepts_credit: false) 这样的查询不会返回此类记录。 FALSE != NULL 在数据库中。
    • 更多信息在这里:stackoverflow.com/questions/5170008/…
    • 非常感谢。这是一个很好的解释!
    【解决方案2】:

    我认为您可能忘记了运行迁移。我认为你应该运行:rake db:migrate:reset

    尝试运行,rake db:migrate,然后,rake db:seed。 如果这个答案没有帮助,我提前道歉。

    【讨论】:

    • 据我了解,rake db:reset 删除数据库,创建它,然后按顺序运行所有迁移,然后为其播种。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多