我必须学习如何在rails 4.1.0(Ruby 2.0)中创建模型。我需要创建2个模型:Category和Post(一对多)。好的,我的步骤:
$ rails new test_work
$ cd test_work/
$ rails generate model Category \
> name:string
$ rails generate model Post \
> message:text
然后我以这样的方式改变了我的模型文件:
class Category < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :category
end
然后我运行rake db:migrate并打开rails console。在此之后,我添加了新的类别:
category = Category.create name: "fghjk"
我想确定,我还没有收到帖子:
2.0.0-p451 :002 > category.posts
Post Load (0.3ms) SELECT "posts".* FROM "posts" WHERE "posts"."category_id" = ? [[nil, 1]]
SQLite3::SQLException: no such column: posts.category_id: SELECT "posts".* FROM "posts" WHERE "posts"."category_id" = ?
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: posts.category_id: SELECT "posts".* FROM "posts" WHERE "posts"."category_id" = ?
问题是什么?
2.0.0-p451 :008 > category.posts.create(message: "dsfsfdfs")
(0.2ms) begin transaction
(0.2ms) rollback transaction
ActiveRecord::UnknownAttributeError: unknown attribute: category_id
答案 0 :(得分:1)
您未在category_id
表格中创建posts
字段,以允许帖子和类别相关联。更新posts
中的db/migrate/##_create_posts_table.rb
迁移并添加以下内容:
t.references :category
或者,如果你重新开始,你应该像这样生成Post
模型:
rails generate model Post message:text category:references
您必须使用rake db:rollback
撤消迁移,然后再次运行rake db:migrate
。
您可以使用category_id
字段添加其他迁移,然后您无需回滚迁移:
rails generate migration AddCategoryToPost category:references