ruby on rails. seed error while creating objects with association

823 views Asked by At

I am trying to create a task management prototype. I created two models - Category and Task, while tasks belong to category and a category can contain many tasks.

class Category < ActiveRecord::Base
  has_many :tasks
end

And

class Task < ActiveRecord::Base
    belongs_to :category
end

Then in migration file

class CreateTasks < ActiveRecord::Migration
  def change
    create_table :tasks do |t|
      t.string :name
      t.string :note
      t.references :category
      t.timestamps null: false
    end
  end
end

and

class CreateCategories < ActiveRecord::Migration
  def change
    create_table :categories do |t|
      t.string :name
      t.string :description
      t.timestamps null: false
    end 
  end
end

I tried to seed some data to start working with, here's the seed file

c1 = Category.create(name: 'Category1')

Task.create(name: 'TASK1', category_id: c1.id)

However it gives me the error:

rake db:seed   
rake aborted!
ActiveRecord::UnknownAttributeError: unknown attribute 'category_id' for Task.

I have tried the following as well

Task.create(name: 'TASK1', category: c1)
Task.create(name: 'TASK1', category: c1.id)

And I got the error

rake db:seed
rake aborted!
ActiveRecord::AssociationTypeMismatch: Category(#70174570341620) expected, got Fixnum(#70174565126780)

However in the browser, @category.id does load and display (as a two digit number 33).

Think I might be missing something obvious but can't figure out why I can't create the task associated with the specific category c1 in from the seeding the data

1

There are 1 answers

0
Felipe Valdivia On BEST ANSWER

just need to pass the object:

c1 = Category.find_or_create_by(name: 'Category1')

I recommend to use find_or_create_by for not create twice the same data

Task.find_or_create_by(name: 'TASK1', category: c1)

if not work try create the same data in the console

I hope help you