Search code examples
ruby-on-railsrubynomethoderrorruby-on-rails-5.2

NoMethodError (undefined method `each' for #<Todo:0x000055f72c0896b0>)


I'm trying to make simple web app with projects and some tasks for this project. Ubuntu 18.10 on Oracle VM, Ruby 2.5.3p105, Rails 5.2.2, Postgresql 10

When i try to test it in rails console i can create project with no problems, but when i try to create todo i get this

2.5.3 :001 > project = Project.create title: "My project"
   (0.2ms)  BEGIN
  Project Create (0.8ms)  INSERT INTO "projects" ("title", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["title", "My project"], ["created_at", "2018-12-28 20:10:57.929619"], ["updated_at", "2018-12-28 20:10:57.929619"]]
   (15.1ms)  COMMIT
 => #<Project id: 2, title: "My project", created_at: "2018-12-28 20:10:57", updated_at: "2018-12-28 20:10:57"> 
2.5.3 :002 > todo = Todo.create text: "Some random task"
   (0.3ms)  BEGIN
   (0.3ms)  ROLLBACK
 => #<Todo id: nil, project_id: nil, text: "Some random task", created_at: nil, updated_at: nil, isCompleted: false> 
2.5.3 :003 > project.todos = Todo.create text: "Some random task"
   (0.3ms)  BEGIN
   (0.2ms)  ROLLBACK
Traceback (most recent call last):
        1: from (irb):3
NoMethodError (undefined method `each' for #<Todo:0x00007f7ab02c91d8>)

This is my migrate

class CreateProjects < ActiveRecord::Migration[5.2]
  def change
    create_table :projects do |t|
      t.string :title
      t.timestamps
    end

    create_table :todos do |t|
      t.belongs_to :project, index: true
      t.text :text
      t.timestamps
    end
    add_column :todos, :isCompleted, :boolean, :default => false
  end
end

This is my project and todo models

class Project < ApplicationRecord
  has_many :todos
end

class Todo < ApplicationRecord
  belongs_to :project
end 

So what am i doing wrong and how can i get it to work?


Solution

  • what am i doing wrong

    You're passing a single todo into a method that expects a collection of todos.

    how can i get it to work?

    Here's a more idiomatic way:

    project.todos.create(text: "Some random task")
    

    Read this guide, it will be helpful: https://guides.rubyonrails.org/association_basics.html