0

当我使用 t.string 或 t.number 时,我无法创建数据库列。

当我 rake db:migrate 我得到了这个

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

我认为这是一个非常小的错误,但我无法弄清楚。

期待您的帮助和支持。

谢谢你

4

1 回答 1

2

迁移顶部的这条线是什么?这只是您的问题中的一个错误吗?

ComicBook < ActiveRecord::Base

看起来您将代码放入模型而不是迁移中!?

在 /db/migrate 文件夹中查找顶部应该有类似内容的文件

class CreateComicBooks < ActiveRecord::Migration

看起来您已经使用生成器来创建迁移(这很好)然后运行 ​​rake db:migrate ,这将解释为什么您在 db 中只有 id 和时间戳的表。您可能想要运行 rake db:rollback 然后将您的字段添加到迁移中的 def self.up 部分并重新迁移。

于 2010-09-23T13:11:33.750 回答