是时候为应用程序增加第二个模型了。第二个模型将会用来处理关于文章的评论Comment。
6.1 Generating a Model
我们将会看到之前用过的同样的生成器,在创建Article模型的时候。这一次我们将会创建一个Comment模型,来关联到文章的评论。在命令窗口运行这个命令:
$ rails generate model Comment commenter:string body:text article:references |
这个命令将会产生四个文件:
文件 | 目的 |
db/migrate/20140120201010_create_comments.rb | 数据迁移用来在你的数据库中创建关于评论的数据表 (你的文件名将会包括一个不一样的时间戳) |
app/models/comment.rb | The Comment model |
test/models/comment_test.rb | Testing harness for the comments model |
test/fixtures/comments.yml | Sample comments for use in testing |
首先,来看一下 app/models/comment.rb:
classComment < ActiveRecord::Base belongs_to :article end |
这个和之前你看到的Article模型非常相似。不一样的地方是这行 belongs_to :article,这是建立一个与Active Record的关联。你将会在下一部分的内容中学到一些关于关联的知识。
另外对于模型,Rails同样弄了一个数据迁移来创建一个相对应的数据表:
classCreateComments < ActiveRecord::Migration defchange create_table :commentsdo|t| t.string :commenter t.text :body
# this line adds an integer column called `article_id`. t.references :article, index: true
t.timestamps end end end |
这个t.references建立一个外键用来联系这两个模型。对于这个关联的索引同样被创建在这一列上面。继续来运行这个migration命令:
$ rake db:migrate |
Rails是相当的智能,来产生这些数据迁移的命令,还没在现在的数据库上面运行过,因此在这个例子中你将会看到:
== CreateComments: migrating ================================================= -- create_table(:comments) -> 0.0115s == CreateComments: migrated (0.0119s) ======================================== |
原文来源:http://guides.rubyonrails.org/getting_started.html#adding-a-second-model
—end