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

时间:2019-06-13 15:40:22

标签: ruby-on-rails ruby 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'

relations_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

relations / index.html.slim:

= link_to 'Destroy all data', relations_destroy_member_data_path, method: :delete, data: {confirm: 'Are you sure?'}

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

Couldn't find Relation with 'id'=destroy_member_data

Extracted source (around line #59):

58: def destroy
59:    @relation = Relation.find(params[:id])

有人可以帮助我吗? 预先谢谢你。

1 个答案:

答案 0 :(得分:5)

由于/relations/destroy_member_data/relations/:id的删除路由匹配,因此destroy_member_data被视为ID,并且此路由是在之前定义的

两种解决方法

  • resources :relations
  • 之前移动该自定义路线
  • 这也应该工作而且更干净
resources :relations do
  delete :destroy_member_data, on: :collection
end