得到“未定义的方法`todo_item'”

时间:2016-05-07 09:11:06

标签: ruby-on-rails rest

任何人都可以帮助解决这个问题NoMethodError(未定义的方法`todo_items')?

这是我的控制器文件:

 class Api::TodoItemsController < ApplicationController
 skip_before_filter :verify_authenticity_token
 before_filter :find_todo_list

 def create

 item = @list.todo_items.new(item_params)
if item.save
  render status: 200, json: {
    message: "Successfully created To-do Item.",
    todo_list: @list,
    todo_item: item
  }.to_json
else
  render status: 422, json: {
    message: "To-do Item creation failed.",
    errors: item.errors
  }.to_json
end
end

private

def item_params
  params.require("todo_item").permit("content")
end

def find_todo_list
  @list = TodoList.find(params[:todo_list_id])
end

这是我的TodoList模型代码:

class TodoList < ActiveRecord::Base
end

这是我的TodoItem模型代码:

class TodoItem < ActiveRecord::Base
end

这是未定义方法todo_items的错误消息:

Started POST "/api/todo_lists/5/todo_items/" for ::1 at 2016-05-07     16:57:45 +0800
ActiveRecord::SchemaMigration Load (0.1ms)  SELECT "schema_migrations".* FROM "schema_migrations"
 Processing by Api::TodoItemsController#create as JSON
 Parameters: {"content"=>"new", "todo_list_id"=>"5", "todo_item"=>{"content"=>"new"}}
 TodoList Load (0.2ms)  SELECT  "todo_lists".* FROM "todo_lists" WHERE "todo_lists"."id" = ? LIMIT 1  [["id", 5]]
 Completed 500 Internal Server Error in 21ms (ActiveRecord: 0.6ms)

 NoMethodError (undefined method `todo_items' for #    <TodoList:0x007f82e2dbc088>):
 app/controllers/api/todo_items_controller.rb:6:in `create'

谢谢。

1 个答案:

答案 0 :(得分:0)

您是否在TodoList模型中添加了 todo_items

has_many:todo_items