ActionController :: UrlGenerationError没有嵌套资源的路由匹配

时间:2014-09-24 19:55:06

标签: ruby-on-rails ruby-on-rails-4

我有一个表单,其中包含一个用户列表,其中每个用户都有一个相应的复选框。单击按钮将删除所选的以下内容。

以下是用户下的嵌套资源,我的控制器中有一个destroy方法,当我做rake路由时,我可以看到对应于以下的路径#dump action但是当加载以下列表页面时它会抛出没有路由匹配错误。

routes.rb中:

    resources :users do
     resources :followings
     resources :events
    end

following_controller.rb:

    class FollowingsController < ApplicationController

    def index  
     @followings = Following.findFollowings(params.has_key?("user_id") ? params[:user_id] : current_user.id)
     @following = Following.new
    end

   def destroy
     Following.any_in(:following_id => params[:id]).destroy_all
     render index
   end

   end

index.html.haml:

    = form_for(@following, url: {action: 'destroy'}, :html => {:method => :delete, :role => 'form'}) do |f|
      - @followings.each do |following|
      = f.check_box "following_id"
      = f.submit  "Delete"

rake routes:

    user_followings GET    /users/:user_id/followings(.:format)          followings#index
                     POST   /users/:user_id/followings(.:format)          followings#create
  new_user_following GET    /users/:user_id/followings/new(.:format)      followings#new
 edit_user_following GET    /users/:user_id/followings/:id/edit(.:format) followings#edit
      user_following GET    /users/:user_id/followings/:id(.:format)      followings#show
                     PATCH  /users/:user_id/followings/:id(.:format)      followings#update
                     PUT    /users/:user_id/followings/:id(.:format)      followings#update
                     DELETE /users/:user_id/followings/:id(.:format)      followings#destroy

错误堆栈:

没有路线匹配{:action=>"destroy", :controller=>"followings", :user_id=>"540f5c6b7072610a4c040000"} 提取的来源(第9行):

6  %ul
7      = render partial: "shared/npo_menu", locals: {item: 'followings'}
8  %section.following.notifications
9      = form_for(@following, url: {action: 'destroy'}, :html => {:method => :delete, :role => 'form'}) do |f|
10       .container
11          .row.manipulate
12              .pull-left

谢谢!

1 个答案:

答案 0 :(得分:0)

解决了路由问题。对于多次删除,路由必须声明为集合。以下是有效的变化 -

的routes.rb

    resources :users do
      resources :followings do
        collection do
         delete 'destroy_multiple'
        end    
      end
      resources :events
   end 

followings_controller.rb

    def destroy_multiple
      Following.any_in(:following_id => params[:id]).destroy_all

      respond_to do |format|
      format.html { redirect_to user_followings_path }
      format.json { head :no_content }
   end

index.haml.html

    = form_tag destroy_multiple_user_followings_path, method: :delete do