为什么我的应用程序使用destroy而不是自定义操作?

Ana*_*pin 0 ruby ruby-on-rails ruby-on-rails-5

我是Ruby的新手。对不起我的英语不好。

我需要创建用于销毁所有用户对象的按钮(名为Relations和ListRelations的模型)。

这是我的config / routes.rb的一部分:

  devise_for :users, controllers: { omniauth_callbacks: 'omniauth_callbacks' }
  resources :relations
  resources :list_relations
  delete '/relations/destroy_member_data' => 'relations#destroy_member_data'
Run Code Online (Sandbox Code Playgroud)

Relationships_controller.rb

  def destroy_member_data
    if current_user.relations.destroy_all && current_user.list_relations.destroy_all
      redirect_to(relations_path, :notice => 'All relations were successfully destroyed')
    else
      redirect_to(relations_path, :warning => 'Something went wrong. Please, try again.')
    end
  end
Run Code Online (Sandbox Code Playgroud)

Relationships / index.html.slim:

= link_to 'Destroy all data', relations_destroy_member_data_path, method: :delete, data: {confirm: 'Are you sure?'}
Run Code Online (Sandbox Code Playgroud)

当我单击此链接时,出现此错误:

Couldn't find Relation with 'id'=destroy_member_data

Extracted source (around line #59):

58: def destroy
59:    @relation = Relation.find(params[:id])
Run Code Online (Sandbox Code Playgroud)

谁能帮我?先感谢您。

Urs*_*sus 5

Because /relations/destroy_member_data matches the delete route for /relations/:id, destroy_member_data is seen as the id and this route is defined before

Two ways to solve this

  • Move that custom route before resources :relations
  • This should work too and it's cleaner
resources :relations do
  delete :destroy_member_data, on: :collection
end
Run Code Online (Sandbox Code Playgroud)