Ruby on Rail s:获取NoMethodError

时间:2015-10-05 05:21:30

标签: ruby-on-rails ruby

ERROR

Failure/Error: click_link "New Todo Item"   
 NoMethodError:   
 undefined method `permit' for nil:NilClass 
 # ./app/controllers/todo_items_controller.rb:25:in `todo_item_params' 
 # ./app/controllers/todo_items_controller.rb:13:in `new'    
 # ./spec/features/todo_items/create_spec.rb:15:in `block (2 levels) in <top
(required)>'

我的create_spec.rb

require 'spec_helper'

describe "Adding todo items" do
  let!(:todo_list) { TodoList.create(title: "Grocery list", description: "Groceries") }

  def visit_todo_list(list)
    visit "/todo_lists"
    within "#todo_list_#{list.id}" do
      click_link "List Items"
    end
  end

  it "is successful with valid content" do
    visit_todo_list(todo_list)
    click_link "New Todo Item"
    fill_in "Content", with: "Milk"
    click_button "Save"
    expect(page).to have_content("Added todo list item.")
    within("ul.todo_items") do
      expect(page).to have_content("Milk")
    end
  end

end

my todo_items_controller.rb

class TodoItemsController < ApplicationController
  def index
    @todo_list = TodoList.find(params[:todo_list_id])
  end

  def new
    @todo_list = TodoList.find(params[:todo_list_id])
    @todo_item = @todo_list.todo_items.new
  end   

  def new
    @todo_list = TodoList.find(params[:todo_list_id])
    @todo_item = @todo_list.todo_items.new(todo_item_params)
    if @todo_item.save
        flash[:success] = "Added todo list item."
        redirect_to todo_list_todo_item_path
    else
        flash[:error] = "There was a problem adding that todo list item."
        render action: :new 
    end 
  end

  private 
  def todo_item_params
    params[:todo_item].permit(:content)
  end   
end

2 个答案:

答案 0 :(得分:1)

尝试将todo_item_params更改为:

private 
def todo_item_params
  params.require(:todo_item).permit(:content)
end  

答案 1 :(得分:1)

我认为这个错误有两个原因:

第一种是todo_item_params方法。您必须按照pavan的建议进行更改:

def todo_item_params
  params.require(:todo_item).permit(:content)
end

第二个问题是你的控制器中有两个new方法。没有createsaveupdate方法。