NoMethodError(#<todo:0x000055f72c0896b0>的未定义方法“每个”)

时间:2018-12-28 20:15:52

标签: ruby-on-rails ruby nomethoderror ruby-on-rails-5.2

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

当我尝试在Rails控制台中对其进行测试时,我可以毫无问题地创建项目,但是当我尝试创建todo时,我会得到这个

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

这是我的迁移

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 

那我在做错什么,如何使它正常工作?

1 个答案:

答案 0 :(得分:2)

  

我在做什么错

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

  

我如何使它工作?

这是一种更惯用的方式:

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

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