销毁many_to_many关系Rails

时间:2017-11-25 20:52:08

标签: ruby-on-rails

在我的groups控制器中,我调用usergroups,其中包含以下架构。

create_table "usergroups", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
  t.bigint "user_id"
  t.bigint "group_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.index ["group_id"], name: "index_usergroups_on_group_id"
  t.index ["user_id"], name: "index_usergroups_on_user_id"
end

我想销毁usergroup控制器中的groups条记录之一。我怎样才能做到这一点?我尝试了以下代码,但遇到了这个错误:

undefined method 'usergroup'

这位于“组视图”文件的show.html.erb中。

<%= link_to 'Remove', usergroup(group_id: @group), method: :delete, data: { confirm: 'Are you sure?' } %>

1 个答案:

答案 0 :(得分:0)

您需要创建一个控制器操作来销毁所有记录。

show.html.erb

<%= link_to 'Remove', {controller: "groups", action: "delete_usergroups",
group_id: group}, data: { confirm: 'Are you sure?' } %>

groups_controller.rb

def delete_usergroups
  Usergroup.where(group_id: params[:id]).delete_all
  redirect_to groups_path
end

的routes.rb

get 'groups/delete_usergroups/:id', to: 'groups#delete_usergroups'