删除选中的项目Rails

时间:2019-01-18 08:56:00

标签: ruby-on-rails checkbox action

我有一个数组selected_ids [],其中包含表单中的项目ID,单击按钮时可以在控制台中看到它们,但是无法删除它们。

我的表单:

  

    <% for task in @tasks.where(active: true) %>
      <li class="task">
        <%=  check_box_tag 'selected_ids[]', task.id, false, class: 'selectable' %>
        <%= link_to task.title, task, class: "task-title text-dark" %>
      </li>
    <% end %>

  </ul>

我的动作

def delete_all
    Task.where(id: params[:selected_ids]).destroy_all
    @tasks = Task.where(user_id: current_user)
    render "index"
  end

我的路线:

resources :tasks do
    get :delete_all, on: :collection
  end

控制台,单击按钮时:

Started DELETE "/tasks/delete_all" for 127.0.0.1 at 2019-01-18 10:44:18 +0200
Processing by TasksController#destroy as HTML
  Parameters: {"utf8"=>"?", "authenticity_token"=>"3BlLqPDnC9IzaVqnCv6qO0KkKP7VNBU9yEnmm8eAKyb76f5eCEIYUq9Gxx4YNbtbcJo0AEi2c/ORs2E87sg0Aw==", "commit"=>"Delete selected", "selected_ids"=>["2", "1"], "id"=>"delete_all"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ? app/controllers/tasks_controller.rb:2
  Task Load (0.3ms)  SELECT  "tasks".* FROM "tasks" WHERE "tasks"."id" = ? ORDER BY "tasks"."id" ASC LIMIT ?  [["id", 0], ["LIMIT", 1]]
  ? app/controllers/tasks_controller.rb:101
  Rendering public/404.html within layouts/application
  Rendered public/404.html within layouts/application (0.4ms)
Filter chain halted as :set_task rendered or redirected
Completed 404 Not Found in 682ms (Views: 676.8ms | ActiveRecord: 0.6ms)

1 个答案:

答案 0 :(得分:1)

您的控制器中有一个名为before_action的{​​{1}}。这是将在set_task之前运行的代码。如果您不希望它在delete_all上运行,请将delete_all添加到, except: [:delete_all]行:

示例:

before_action

如果将# change this line somewhere near the top of your controller before_action :set_task, except: [:delete_all] 设置为before_action之类的其他位置,则可以将此行添加到ApplicationController中,以达到相同的效果:

TasksController