0

I have two models 'Tutorial' and 'Tutorialcategory'

class Tutorialcategory < ActiveRecord::Base
has_many :tutorials


class Tutorial < ActiveRecord::Base
    belongs_to :tutorialcategory

Tutorials are associated with multiple categories like html,rubyonrails where html and ruby on rails are tutorialcategories

followings are migrations

class CreateTutorials < ActiveRecord::Migration
  def change
    create_table :tutorials,force: true do |t|
      t.string :title
      t.text :body
      t.integer :rating
      t.string :videoid
      t.belongs_to :tutorialcategory

      t.timestamps
    end
  end
end


class CreateTutorialcategories < ActiveRecord::Migration
  def change
    create_table :tutorialcategories do |t|
      t.string :title

      t.timestamps null:false
    end
  end
end

All tutorials are listing properly on index page but when I see category page it gives me following error

PG::Error: ERROR:  column tutorials.tutorialcategory_id does not exist
Vikram
  • 3,171
  • 7
  • 37
  • 67

1 Answers1

0

I have no idea why you named your model Tutorialcategory instead of TutorialCategory which follow Rails naming convention and make it easier to understand.

Firstly, rollback your db one step

rake db:rollback

Change your migration file to:

class CreateTutorials < ActiveRecord::Migration
  def change
    create_table :tutorials,force: true do |t|
      t.string :title
      t.text :body
      t.integer :rating
      t.string :videoid
      t.belongs_to :tutorial_category, index: true

      t.timestamps
    end
  end
end


class CreateTutorialCategories < ActiveRecord::Migration
  def change
    create_table :tutorial_categories do |t|
      t.string :title

      t.timestamps null:false
    end
  end
end

Run the migration again and edit your model to match with new schema.

class TutorialCategory < ActiveRecord::Base
  has_many :tutorials


class Tutorial < ActiveRecord::Base
  belongs_to :tutorial_category
Long Nguyen
  • 11,075
  • 2
  • 18
  • 25
  • yes he is not using correct naming conventions but still why error? it looks code is perfect isnt it? – Guru Nov 18 '15 at 09:05
  • @Guru Agreed. But when we have no clue, let try if follow naming convention make it works because of the Rails way: `convention over configuration` – Long Nguyen Nov 18 '15 at 09:10
  • I think I am very close to it, just not getting how to connect multiple to multiple. As per rails doc belongs_to is for one to many but I have many to many which can be done with has_and_belongs_to_many but then how will I get list tutorials for a category. – Vikram Nov 18 '15 at 09:48
  • Question was for one to many and code also shows same. anyway if you want to achive m2m use has_many through. tell me if you stuck anywhere – Guru Nov 18 '15 at 11:53