【问题标题】:Delete checked items Rails删除选中的项目 Rails
【发布时间】:2019-01-18 18:22:33
【问题描述】:

我有数组 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)

【问题讨论】:

    标签: ruby-on-rails checkbox action


    【解决方案1】:

    您的控制器中有一个名为set_taskbefore_action。这是将在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 以实现相同效果:

     skip_before_action :set_task, only: [:delete_all]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多