Search code examples
rubyruby-on-rails-4models

(Beginner)RubyOnRails: MODELS


I have to learn how to create models in rails 4.1.0 (Ruby 2.0). I need create 2 models: Category and Post (one-to-many). Ok, my steps:

$ rails new test_work
$ cd test_work/
$ rails generate model Category \
> name:string
$ rails generate model Post \
> message:text

Then I changed my model files in such a way:

class Category < ActiveRecord::Base
  has_many :posts
end
class Post < ActiveRecord::Base
  belongs_to :category
end

Then I run rake db:migrate and open rails console. After this I'm adding new Category:

category = Category.create name: "fghjk"

I want to be sure, that i haven't got posts yet:

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" = ?

What's the problem?

2.0.0-p451 :008 >   category.posts.create(message: "dsfsfdfs")
   (0.2ms)  begin transaction
   (0.2ms)  rollback transaction
ActiveRecord::UnknownAttributeError: unknown attribute: category_id

Solution

  • You didn’t create a category_id field in the posts table to allow posts and categories to be related. Update the posts migration in db/migrate/##_create_posts_table.rb and add this:

    t.references :category
    

    Or, if you start over, you should generate the Post model like this:

    rails generate model Post message:text category:references
    

    You’ll have to undo your migrations with rake db:rollback and then run rake db:migrate again.

    You could add another migration with the category_id field and then you wouldn’t need to roll back the migrations:

    rails generate migration AddCategoryToPost category:references