【问题标题】:Seeding fails upon `enum`在“枚举”上播种失败
【发布时间】:2015-12-28 21:18:31
【问题描述】:

我在使用 enum 时遇到问题。我看了documentation 但不明白我做错了什么(对不起,我是新手)。我有我的模型文件:

enum origin: [ :website, :stand, :other ]

在我的种子文件中,我创建了一个新记录,其中一个键值对是origin: "website"

content = Faker::Lorem.paragraphs(2)
author.articles.create!( title: "Title",
                         origin: "website",
                         content: content )

播种后会产生错误:

ActiveRecord::SubclassNotFound: Invalid single-table inheritance type: website is not a subclass of Article

这个错误的原因可能是什么?

更新:我在这里阅读相同的问题:https://github.com/rails/rails/issues/14136。但我不明白。有人可以解释一下吗?

文章.rb:

class Article < ActiveRecord::Base
  belongs_to :author
  has_many :links
  validates :author_id, presence: true
end

【问题讨论】:

  • 您是否将模型中的继承列更改为原点?
  • 不,我在提到的 github 帖子上读到过,但我不明白这是什么意思。
  • 请查看我的更新答案
  • 如果这不起作用,请在您的问题中包含 Article.rb 模型
  • 我在帖子中添加了 Article.rb

标签: ruby-on-rails ruby validation ruby-on-rails-4 seeding


【解决方案1】:

这应该可行:

author.articles.create!( title: "Title",
                         origin: :website,
                         content: content )

枚举来源:http://edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html

如需深入了解枚举:https://hackhands.com/ruby-on-enums-queries-and-rails-4-1/

【讨论】:

  • 谢谢,你的意思是我的种子文件中需要origin: 0 吗?如果我这样做,我会在播种时收到错误消息:NoMethodError: undefined method 'safe_constantize' for 0:Fixnum.
  • 谢谢,我在种子里把它改成了origin: :website。但这会产生错误:NoMethodError: undefined method 'safe_constantize' for :website:Symbol。您提到的文档似乎确实表明您需要origin: 0,,但如上所述也不起作用。
  • 好的,我找到了,问题是列名之一。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
  • 2012-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-03
相关资源
最近更新 更多