2017-03-05 63 views
-1

我得到了todos#index中的NoMethodError,並且找不到原因。這裏是我的index.html.erb文件中的代碼:Ruby on Rails:在todos中的NoMethodError#index

<h1>Listing all Todos</h1> 

<p> 

    <%= link_to "Create a Todo", new_todo_path %> 
</p> 

<table> 
    <tr> 
    <th>Name</th> 
    <th>Description</th> 
    </tr> 
    <% @todos.each do |todo| %> 
    <tr> 
     <td><%= todo.name %></td> 
     <td><%= todo.description %></td> 
     <td><%= link_to 'Edit', edit_todo_path(todo) %></td> 
     <td><%= link_to 'Show', todo_path(todo) %></td> 
     <td><%= link_to 'Delete', todo_path(todo), method: :delete, data: {confirm: "Are you sure?"} %></td> 
    </tr> 
    <% end %> 
</table> 

todos_controller.rb:

class TodosController < ApplicationController 
    before_action :set_todo, only: [:edit, :update, :show, :destroy] 

    def new 
    @todo = Todo.new 
    end 

    def create 
    @todo = Todo.new(todo_params) 
    if @todo.save 
     flash[:notice] = "Todo was created successfully" 
     redirect_to todo_path(@todo) 
    else 
     render 'new' 
    end 
    end 

    def show 
    end 

    def edit 
    end 

    def update 
    if @todo.update(todo_params) 
     flash[:notice] = "Todo was successfully updated" 
     redirect_to todo_path(@todo) 
    else 
     render 'edit' 
    end 
    end 
end 

    def index 
     @todos = Todo.all 
    end 

    def destroy 
     @todo.destroy 
     flash[:notice] = "Todo was deleted successfully" 
     redirect_to todos_path 
    end 

    private 

    def set_todo 
     @todo = Todo.find(params[:id]) 
    end 

    def todo_params 
     params.require(:todo).permit(:name, :description) 
    end 
+2

你可以發佈你的'todos'控制器嗎? – Mark

+0

嗨,我剛剛發佈了todos_controller.rb代碼。 – pdenlinger

+0

太好了,謝謝!我在下面回答你的問題。 – Mark

回答

2

它看起來就像你在錯誤的地方有一個end。我只是固定你的控制器。在您定義index操作之前,您會過早結束您的class TodosController

class TodosController < ApplicationController 
    before_action :set_todo, only: [:edit, :update, :show, :destroy] 

    def new 
    @todo = Todo.new 
    end 

    def create 
    @todo = Todo.new(todo_params) 
    if @todo.save 
     flash[:notice] = "Todo was created successfully" 
     redirect_to todo_path(@todo) 
    else 
     render 'new' 
    end 
    end 

    def show 
    end 

    def edit 
    end 

    def update 
    if @todo.update(todo_params) 
     flash[:notice] = "Todo was successfully updated" 
     redirect_to todo_path(@todo) 
    else 
     render 'edit' 
    end 
    end 

    def index 
    @todos = Todo.all 
    end 

    def destroy 
    @todo.destroy 
    flash[:notice] = "Todo was deleted successfully" 
    redirect_to todos_path 
    end 

    private 

    def set_todo 
    @todo = Todo.find(params[:id]) 
    end 

    def todo_params 
    params.require(:todo).permit(:name, :description) 
    end 
end  
+0

工作正常;非常感謝你! – pdenlinger