【问题标题】:Seeding fails: "field can't be blank" but I'm seeding with a value播种失败:“字段不能为空”,但我正在播种一个值
【发布时间】:2016-01-16 11:18:45
【问题描述】:

我有一个Article 表的必填字段:

t.string  :article_type, null: false

在模型中:

validates :article_type,  presence: true
enum article_type:        [ :type1, :type2, :type3, :type4, :type5 ]

在我的种子中我有:

books = Book.all
books.each do |book|
  title = Faker::Lorem.sentence(3)
  article_type = ["type1", "type2", "type3", "type4", "type5"].sample
  book.articles.create!( title: title,
                         article_type: article_type )
end

问题:create 行产生错误:ActiveRecord::RecordInvalid: Validation failed: Article type can't be blank。这可能是什么原因造成的? (我可以确认.sample 行有效并选择了五种类型之一)

更新:如果我将 article_type 从字符串更改为整数,它可以工作。我应该怎么办?因为它不是真正的整数,是不是……?

【问题讨论】:

  • 试试这个:article_type = -> { ["type1", "type2", "type3", "type4", "type5"].sample }.call
  • 谢谢,create 行失败并出现错误:``block in '`
  • 嗯,看不出有什么原因发生这种情况
  • 我已经用完整的方法扩展了原始帖子(添加了each 循环),这也许可以解释错误?
  • 这个怎么样? article_type = -> { ["type1", "type2", "type3", "type4", "type5"].sample }.call title = -> { Faker::Lorem.sentence(3) }.call books.each { |book| book.articles.create!(title: title,article_type: article_type) }

标签: ruby-on-rails validation seeding


【解决方案1】:

Rails enum 期望对应的 db 列是整数,但你的是字符串。

所以要么更改为整数,要么用值验证替换枚举。

【讨论】:

  • enum 行替换为validates_inclusion_of :article_type, :in => ["type1", "type2", "type3", "type4", "type5"] 是正确的代码吗?
  • @Marty 是的。枚举还为每个值和方法创建范围,例如type1?
【解决方案2】:

尝试隔离错误。看看这个种子是否没有任何问题,然后继续分割?

article_type = "type1"
book.articles.create!( title: title,
                         article_type: article_type )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 2013-05-06
    • 2017-03-23
    • 2018-06-28
    • 2021-07-10
    • 2021-08-13
    • 1970-01-01
    相关资源
    最近更新 更多