当我运行rake:db migrate命令时,出现“Uninitialized constant CreateArticles”

我创build了一个模型ruby脚本/生成模型文章(简单的enuff)

这里是迁移文件create_articles.rb:

def self.up create_table :articles do |t| t.column :user_id, :integer t.column :title, :string t.column :synopsis, :text, :limit => 1000 t.column :body, :text, :limit => 20000 t.column :published, :boolean, :default => false t.column :created_at, :datetime t.column :updated_at, :datetime t.column :published_at, :datetime t.column :category_id, :integer end def self.down drop_table :articles end end 

当我运行rake:db migrate命令时,我收到一个错误耙子中止! “未初始化的常量CreateArticles”。

有谁知道为什么这个错误不断发生?

确保你的文件名和类名称是相同的(除了类名称是骆驼壳)。你的迁移文件的内容应该看起来像这样,简化了一下:

 #20090106022023_create_articles.rb class CreateArticles < ActiveRecord::Migration def self.up create_table :articles do |t| t.belongs_to :user, :category t.string :title t.text :synopsis, :limit => 1000 t.text :body, :limit => 20000 t.boolean :published, :default => false t.datetime :published_at t.timestamps end end def self.down drop_table :articles end end 

如果您收到此错误,并不是因为迁移文件名称,还有另一种可能的解决scheme。 像这样直接在迁移中打开这个类:

 class SomeClass < ActiveRecord::Base; end 

现在应该可以在迁移中使用SomeClass

如果您的类名不匹配来自config/initializers/inflections.rb变形(如缩写),可能会得到给定的错误。

例如,如果你的变化包括:

 ActiveSupport::Inflector.inflections(:en) do |inflect| inflect.acronym 'DOG' end 

那么您可能需要确保迁移中的class级是:

class CreateDOGHouses < ActiveRecord::Migration[5.0]

而不是:

class CreateDogHouses < ActiveRecord::Migration[5.0]

不是很常见,但是如果你生成一个迁移或者一个模型或者其他东西,然后把它的一部分添加到变形之后,可能会发生。 (这里的例子会导致NameError: uninitialized constant CreateDOGHouses如果你的类名是CreateDogHouses ,至less在Rails 5中)