2014-09-29 4 views
3

В Todo есть много элементов. Я пытаюсь добавить ссылку для удаления элемента из списка задач. Я попробовал варианты, чтобы найти элемент по id в списке todo, и я не могу понять это. Это самая последняя ошибка, основанная на изменениях, которые я сделал. Я не знаю, как это исправить.Как добавить маршрут удаления с вложенными ресурсами rails 4

сообщение

Ошибка: No route matches [DELETE] "/todos/6/items"

Todo Контроллер:

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

    # GET /todos 
    # GET /todos.json 
    def index 
    @todos = Todo.all 
    @todo = Todo.new 
    end 

    # GET /todos/1 
    # GET /todos/1.json 
    def show 
    end 

    # GET /todos/new 
    def new 
    @todo = Todo.new 
    #3.times{@todo.items.build} 
    end 

    # GET /todos/1/edit 
    def edit 
    end 

    # POST /todos 
    # POST /todos.json 
    def create 
    @todo = Todo.new(todo_params) 
    #@todo.items.build 

    respond_to do |format| 
     if @todo.save 
     format.html { redirect_to todos_path, notice: 'Todo was successfully created.' } 
     format.json { render :show, status: :created, location: @todo } 
     else 
     format.html { render :new } 
     format.json { render json: @todo.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PATCH/PUT /todos/1 
    # PATCH/PUT /todos/1.json 
    def update 
    @todo = Todo.find(params[:id]) 
    respond_to do |format| 
     if @todo.update(todo_params) 
     format.html { redirect_to @todo, notice: 'Todo was successfully updated.' } 
     format.json { render :show, status: :ok, location: @todo } 
     else 
     format.html { render :edit } 
     format.json { render json: @todo.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /todos/1 
    # DELETE /todos/1.json 
    def destroy 
    @todo.destroy 
    @todo.items.destroy 
    respond_to do |format| 
     format.html { redirect_to todos_url, notice: 'Todo was successfully destroyed.' } 
     format.json { head :no_content } 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_todo 
     @todo = Todo.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def todo_params 
     params.require(:todo).permit(:title, :completed, items_attributes: [:content,:completed, :_destroy]) 
    end 
end 

Элементы контроллера:

class ItemsController < ApplicationController 
    before_action :set_item, only: [:show, :edit, :update, :destroy] 
    before_action :set_todo 
    respond_to :html, :js 

    # GET /items 
    # GET /items.json 
    def index 
    @items = Item.all 
    end 

    # GET /items/1 
    # GET /items/1.json 
    def show 
    @item = Item.find(params[:id]) 
    end 

    # GET /items/new 
    def new 
    @item = @todo.items.build 
    end 

    # GET /items/1/edit 
    def edit 
    @item = Items.find(params[:id]) 
    end 

    # POST /items 
    # POST /items.json 
    def create 
    @item = @todo.items.build(item_params) 

    respond_to do |format| 
     if @item.save 
     format.html { redirect_to [@todo,@item], notice: 'Item was successfully created.' } 
     format.json { render :show, status: :created, location: @item } 
     else 
     format.html { render :new } 
     format.json { render json: @item.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PATCH/PUT /items/1 
    # PATCH/PUT /items/1.json 
    def update 
    @item = Item.find(params[:id]) 
    respond_to do |format| 
     if @item.update(item_params) 
     format.html { redirect_to [@todo, @item], notice: 'Item was successfully updated.' } 
     format.json { render :show, status: :ok, location: @item } 
     else 
     format.html { render :edit } 
     format.json { render json: @item.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /items/1 
    # DELETE /items/1.json 
    def destroy 
    @todo.items.destroy 
    @item = Item.find(params[:id]) 
    @item.destroy 
    respond_to do |format| 
     format.html { redirect_to @todo, notice: 'Item was successfully destroyed.' } 
     format.json { head :no_content } 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_item 
     @item = Item.find(params[:id]) 
    end 

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

    # Never trust parameters from the scary internet, only allow the white list through. 
    def item_params 
     params.require(:item).permit(:content, :todo_id) 
    end 
end 

Маршруты:

 Prefix Verb URI Pattern        Controller#Action 
    todo_items GET /todos/:todo_id/items(.:format)   items#index 
       POST /todos/:todo_id/items(.:format)   items#create 
new_todo_item GET /todos/:todo_id/items/new(.:format)  items#new 
edit_todo_item GET /todos/:todo_id/items/:id/edit(.:format) items#edit 
    todo_item GET /todos/:todo_id/items/:id(.:format)  items#show 
       PATCH /todos/:todo_id/items/:id(.:format)  items#update 
       PUT /todos/:todo_id/items/:id(.:format)  items#update 
       DELETE /todos/:todo_id/items/:id(.:format)  items#destroy 
     todos GET /todos(.:format)       todos#index 
       POST /todos(.:format)       todos#create 
     new_todo GET /todos/new(.:format)      todos#new 
    edit_todo GET /todos/:id/edit(.:format)    todos#edit 
      todo GET /todos/:id(.:format)      todos#show 
       PATCH /todos/:id(.:format)      todos#update 
       PUT /todos/:id(.:format)      todos#update 
       DELETE /todos/:id(.:format)      todos#destroy 

и мой индекс страницы:

<h1>Listing todos</h1> 
<ul> 
    <% @todos.each do |todo| %> 
    <li><%= link_to todo.title ,edit_todo_path(todo)%></li> 
     <ul> 
     <% todo.items.each do |item| %></br> 
      <li><%= item.content %></li> 
      <li><%= link_to 'Delete Item',todo_item_path(item.id), method: :delete, data: { confirm: "Are you sure you want to delete this item?"} %></li> 
     <% end %> 
     </ul> 
    <% end %> 
</ul> 


<%= link_to 'New Todo', new_todo_path %> 
+0

попробуйте сделать это <% = link_to "delete", [@todo, item],: method =>: delete%> –

+0

Я пробовал это во-первых, он дает мне «ActionController :: UrlGenerationError» - никаких маршрутов не соответствует {: действие => "show",: controller => "items",: id => "6",: todo_id => nil} Отсутствующие необходимые ключи: [: todo_id]: 'Idk, почему ему нужен todo_id или почему его попытка маршрутизации показывать? –

+0

Извините ..remove @ symbol и попробуйте <% = link_to "удалить", [todo, item],: method =>: delete%> –

ответ

2

Попробуйте использовать <%= link_to "delete", [todo, item], :method => :delete %>.

+1

Просто объясните, зачем вам это нужно. Взгляните на эту строку в выводе рейковых маршрутов: 'DELETE /todos/:todo_id/items/:id(.:format) items # destroy'. Это маршрут, на который вы пытаетесь попасть, и, как вы заметили, он принимает идентификаторы 'todo_id' и' item' (извлекаются из параметров как просто 'params [: id]'). Поэтому вам нужно указать оба идентификатора в вашем помощнике пути. Ваше оригинальное решение просто дало todo_id, но поскольку вы пытаетесь удалить __item__ из todo, вам нужен и этот элемент. Неявно называемый помощник пути извлекает оба идентификатора из массива Rahul, который вы используете. – Sasha

Смежные вопросы