2016-01-24 4 views
0

Итак, у меня есть вложенные ресурсы. Элементы, принадлежащие счетам, и я пытаюсь уничтожить Элементы, удалив их, когда Счета-фактуры создаются/редактируются.Как правильно маршрутизировать вложенные ресурсы уничтожить действие?

Я могу удалить записи, но когда я это сделаю, запись удаляется из db, но страница не обновляется или не уходит нигде, однако, когда я обновляю страницу вручную, запись удаляется. Я заметил, что в моей консоли я получаю 1500 внутренних ошибок сервера`, и это происходит из-за этой ошибки.

Каков наилучший способ написать действие destroy для вложенных ресурсов?

ActionController::UrlGenerationError at /invoices/100/items/247 
=============================================================== 

> No route matches {:action=>"index", :controller=>"items", :id=>"247", :invoice_id=>"100"} 

app/controllers/items_controller.rb 
``` ruby 
44  end 
45 
46  def destroy 
47  @item = Item.find(params[:id]) 
48  @item.destroy 
>49  redirect_to :action => 'index' 
50  end  

А вот мои грабли маршруты

$ rake routes 
Prefix Verb URI Pattern        Controller#Action 
item_index GET /item/index(.:format)      item#index 
item_show GET /item/show(.:format)      item#show 
item_new GET /item/new(.:format)      item#new 
item_edit GET /item/edit(.:format)      item#edit 
invoice_item DELETE /invoices/:invoice_id/items/:id(.:format) items#destroy 
invoices GET /invoices(.:format)      invoices#index 
     POST /invoices(.:format)      invoices#create 
new_invoice GET /invoices/new(.:format)     invoices#new 
edit_invoice GET /invoices/:id/edit(.:format)    invoices#edit 
invoice GET /invoices/:id(.:format)     invoices#show 
     PATCH /invoices/:id(.:format)     invoices#update 
     PUT /invoices/:id(.:format)     invoices#update 
     DELETE /invoices/:id(.:format)     invoices#destroy 
    root GET / 

Полный элементы управления

class ItemsController < ApplicationController 
    def index 
    @items = Item.all 
    end 

    def show 
    @invoice = Invoice.find(params[:invoice_id]) 
    @item = Item.find(params[:id]) 
    end 

    def new 
    @item = Item.new 
    end 

    def edit 
    @item = Item.find(params[:id]) 
    end 

    def create 
    @item = Item.new(item_params) 

    respond_to do |format| 
     if @item.save 
     format.html { redirect_to @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 

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

    def destroy 
    @item = Item.find(params[:id]) 
    @item.destroy 
    redirect_to :action => 'index' 
    end 

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

    # Never trust parameters from the scary internet, only allow the white list through. 
    def item_params 
     params.require(:item).permit(:item_name, :item_description, :item_cost, :item_quantity, :item_price, :destroy) 
    end 

end 

Вот моя форма

<%= simple_form_for(@invoice) do |f| %> 
<%= f.input_field :company, class: "form-control", id: "1" %> 

<%= f.simple_fields_for :items do |h| %> 
    <div class="duplicatable_nested_form"> 
     <h4>New item</h4> 
     <p>Name</p> 
      <%= h.input_field :item_name, class: "form-control" %> 
      <p>Description</p> 
      <%= h.input_field :item_description, class: "form-control" %> 
      <p>Cost</p> 
      <%= h.input_field :item_cost, class: "form-control cost", id: "price" %> 
      <p>Quantity</p> 
      <%= h.input_field :item_quantity, class: "form-control qty", id: "quantity" %> 
       <td></td> 

      <% if h.object.new_record? %> 
      <%= link_to 'Remove', '', :remote => true, :class => 'destroy_duplicate_nested_form' %> 
      <% else %> 
      <%= link_to 'Remove', invoice_item_path(@invoice, h.object), :method => :delete, :remote => true, :class => 'destroy_duplicate_nested_form' %> 
      <%= h.input :id, as: :hidden %> 
       <% end %> 
    <P class="price_td"><span class="price">650.00</span><span class="subtotal_currency"></span></P> 


    <% end %> 
</div> 

<%= link_to 'Add Another Item', '', :class => 'duplicate_nested_form' %> 
<%= f.button :submit, 'Submit Payment', class: 'btn btn-warning btn-sm', id: "submit_invoice" %> 

А вот мой nested_forms.js.coffee

jQuery ($) -> 

    if $('.duplicatable_nested_form').length 

     nestedForm = $('.duplicatable_nested_form').last().clone() 
           .find("input:text").val("").end() 

     $(".destroy_duplicate_nested_form:first").remove() 

     $('.destroy_duplicate_nested_form').on 'click', (e) -> 
     $(this).closest('.duplicatable_nested_form').slideUp().remove() 

     $('body').on 'click','.destroy_duplicate_nested_form', (e) -> 
     $(this).closest('.duplicatable_nested_form').slideUp().remove() 

     $('.duplicate_nested_form').click (e) -> 
     e.preventDefault() 
     console.log("this is the click"); 
     lastNestedForm = $('.duplicatable_nested_form').last() 
     newNestedForm = $(nestedForm).clone() 
     formsOnPage = $('.duplicatable_nested_form').length 
     $('#updatedAt').fadeOut('new') 
     $(newNestedForm).find('label').each -> 
      oldLabel = $(this).attr 'for' 
      newLabel = oldLabel.replace(new RegExp(/_[0-9]+_/), "_#{formsOnPage}_") 
      $(this).attr 'for', newLabel 

     $(newNestedForm).find('select, input').each -> 
      oldId = $(this).attr 'id' 
      newId = oldId.replace(new RegExp(/_[0-9]+_/), "_#{formsOnPage}_") 
      $(this).attr 'id', newId 

      oldName = $(this).attr 'name' 
      newName = oldName.replace(new RegExp(/\[[0-9]+\]/), "[#{formsOnPage}]") 
      $(this).attr 'name', newName 

     $(newNestedForm).insertAfter(lastNestedForm) 

Мои Маршруты

Rails.application.routes.draw do 

    get 'item/index' 
    get 'item/show' 
    get 'item/new' 
    get 'item/edit' 

    resources :invoices do 
    resources :items, only: :destroy 
    end 

    # The priority is based upon order of creation: first created -> highest priority. 
    # See how all your routes lay out with "rake routes". 

    # You can have the root of your site routed with "root" 
    root 'invoices#index' 

ответ

1

использование _path в redirect

def destroy 
    @item = Item.find(params[:id]) 
    @item.destroy 
    redirect_to item_index_path 
end 

BTW

очень странный маршрут:

invoice_item DELETE /invoices/:invoice_id/items/:id(.:format) items#destroy 

invoice_item в контроллере товаров? уничтожить?

+0

Если я это сделаю, я получаю «Нет маршрутов» [DELETE] »/ item/index« Я также добавил файл маршрутов к моему вопросу. – Aloalo

+0

try 'redirect_to root_path' просто проверьте его –

+0

Если я делаю' redirect_to root_path', я получаю 'Нет совпадений маршрута [DELETE]"/"' – Aloalo