(初学者)RubyOnRails:MODELS

时间:2014-05-18 16:47:18

标签: ruby ruby-on-rails-4 models

我必须学习如何在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

1 个答案:

答案 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