NoMethodError(#<Todo:0x000055f72c0896b0> 的未定义方法“each”)

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

我正在尝试使用项目和该项目的一些任务制作简单的网络应用程序。 Ubuntu Oracle VM 上的 18.10,Ruby 2.5.3p105,Rails 5.2.2,Postgresql 10

当我尝试在 rails 控制台中测试它时,我可以毫无问题地创建项目,但是当我尝试创建待办事项时,我得到了这个

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 (, , ) 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>)

这是我的迁移

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

这是我的项目和待办事项模型

class Project < ApplicationRecord
  has_many :todos
end

class Todo < ApplicationRecord
  belongs_to :project
end 

那么我做错了什么,我怎样才能让它工作?

what am i doing wrong

您正在将单个待办事项传递到需要待办事项集合的方法中。

how can i get it to work?

这里有一个更惯用的方式:

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

阅读本指南,将会有所帮助:https://guides.rubyonrails.org/association_basics.html