2010-09-23 30 views
0

當我使用t.string或t.number時,我無法創建數據庫列。Rails中的簡單數據庫遷移錯誤

當我做耙分貝:遷移我得到這個

C:\Ruby\joker\chapter3>rake db:migrate 
(in C:/Ruby/joker/chapter3) 
== CreateComicBooks: migrating =============================================== 
-- create_table(:comic_books) 
    -> 0.0630s 
== CreateComicBooks: migrated (0.0640s) ====================================== 

我用下面的代碼

class ComicBook < ActiveRecord::Base 
def self.up 
create_table :comic_books do |t| 
t.string :title 
t.string :writer 
t.string :artist 
t.integer :issue 
t.string :publisher 
t.timestamps 
end 
end 

def self.down 
    drop_table :comic_books 
    end 
end 

我也試圖與

class ComicBook < ActiveRecord::Base 
def self.up 
create_table :comic_books do |t| 
t.column "title", :string 
t.column "writer", :string 
t.column "artist", :string 
t.column "issue", :number 
t.column "publisher", :string 
t.timestamps 
end 
end 

def self.down 
# called when a migration is reversed 
    drop_table :comic_books 
    end 
end 

在我的數據庫得到以下輸出

mysql> show tables; 
+-----------------------------------+ 
| Tables_in_comic_books_development | 
+-----------------------------------+ 
| comic_books      | 
| schema_migrations     | 
+-----------------------------------+ 
2 rows in set (0.00 sec) 

mysql> describe comic_books; 
+------------+----------+------+-----+---------+----------------+ 
| Field  | Type  | Null | Key | Default | Extra   | 
+------------+----------+------+-----+---------+----------------+ 
| id   | int(11) | NO | PRI | NULL | auto_increment | 
| created_at | datetime | YES |  | NULL |    | 
| updated_at | datetime | YES |  | NULL |    | 
+------------+----------+------+-----+---------+----------------+ 
3 rows in set (0.01 sec) 

mysql> 

現在,當我試圖創造一個新的紀錄我得到這個

C:\Ruby\joker\chapter3>ruby script/console 
Loading development environment (Rails 2.3.8) 
>> mycb = ComicBook.new 
=> #<ComicBook id: nil, created_at: nil, updated_at: nil> 
>> mycb.title = 'All new' 
NoMethodError: undefined method `title=' for #<ComicBook id: nil, created_at: ni 
l, updated_at: nil> 
     from C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record 
/attribute_methods.rb:259:in `method_missing' 
     from (irb):2 

我認爲它是一個很小的錯誤,但我只是不能想出辦法來的。

期待您的幫助和支持。

謝謝

+1

您正在將模型中的遷移。這是不正確的。參考tsdbrown的答案來解決你的問題。有人已經在你的其他問題中告訴過你...(http://stackoverflow.com/questions/3777645/error-while-creating-new-object-in-rails)。 – Mischa 2010-09-23 13:19:01

回答

2

遷移頂部的這條線是什麼?這只是你的問題中的一個錯誤?

ComicBook < ActiveRecord::Base 

它看起來像你的代碼在模型中,而不是在你的遷移!?

查看/ DB /遷移文件夾應該在頂部

class CreateComicBooks < ActiveRecord::Migration 

它看起來是這樣的文件,就像你使用生成器來創建遷移(這是罰款),然後運行一個rake數據庫:遷移,這將解釋爲什麼你的數據庫中只有id和timestamps表。您可能想運行rake db:rollback,然後將您的字段添加到遷移中的def self.up部分並重新遷移。