2009-01-05 61 views
43

我創建了一個模型Ruby腳本/生成模型文章(簡單句話之後B)當我運行rake:數據庫遷移命令我得到一個錯誤「未初始化的常量CreateArticles」

下面是遷移文件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命令時,收到一個錯誤rake中止! 「未初始化的常量CreateArticles」。

有誰知道爲什麼這個錯誤繼續發生?

+0

你的遷移文件的名稱是什麼,你的類聲明是什麼樣的? – thetacom 2009-01-05 14:14:59

+0

20090106022023_create_articles.rb(遷移文件) ^不會像上面那樣(類聲明) – featureBlend 2009-01-05 14:22:11

回答

91

確保您的文件名和類名說同樣的事情(除了類名駱駝套管)遷移文件.The內容應該是這個樣子,他們簡化有點太:

#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 
2

如果您收到此錯誤並且不是因爲遷移文件名稱,還有另一種可能的解決方案。在遷移中直接打開類如下:

class SomeClass < ActiveRecord::Base; end 

現在應該可以在遷移中使用SomeClass

0

如果您的類名不匹配來自config/initializers/inflections.rb的拐點(如首字母縮寫詞),可能會出現給定的錯誤。

例如,如果你的語調包括:

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

,那麼你可能需要確保在類遷移是:

class CreateDOGHouses < ActiveRecord::Migration[5.0]

而不是:

class CreateDogHouses < ActiveRecord::Migration[5.0]

不是很常見,但是如果您生成遷移或模型或其他東西,然後將其中的一部分添加到變形後可能會發生。 (這裏的例子將導致NameError: uninitialized constant CreateDOGHouses,如果你的類名是CreateDogHouses,至少Rails 5)。

相關問題