首页 > 解决方案 > 如何使用复选框选择表中的行并作为参数传递给控制器

问题描述

我有一个显示项目列表的表格。我试图能够选择此表中的一些项目并传递给我的控制器,我希望只呈现特定选择的项目。

# 'products/index.html.haml'
%table.table
  %thead
    %tr
      %th Select
      %th Id
      %th Short description

  %tbody
    - @products.each do |product|
      %tr
        %td
          %input{ :type=>"checkbox", :checked=>"checked", :name=>"selected_products[]", :value=>product.id}
        %td
        %td= product.id
        %td= product.short_description

= link_to 'View selected', product_path(:selected_ids=>SELECTED_PRODUCT_IDS)

如上所示,它显示了一个表格,其中第一列是一个选中的复选框,其值是其对应的product.id- 我正在尝试将一个由所选 id 组成的数组传递给参数 - 即数组SELECTED_PRODUCT_IDS

# 'controllers/product_controller.rb'
def index
   product_ids = params[:selected_form_datums]
   ...

上面显示了我的控制器可以访问这个数组。我已经看到一些类似问题的答案,建议将其放入 ' form_for' 标签中,但是到目前为止,我所做的所有尝试都失败了。

将不胜感激任何帮助。

标签: ruby-on-rails

解决方案


首先创建一个包含@selected_products.

class ProductsController < ApplicationController
  before_action :set_product, only: [:show, :edit, :update, :destroy]

  # GET /products
  # GET /products.json
  def index
    @products = Product.all
    @selected_products = if params[:product_ids]
      @products.where(id: params[:product_ids])
    else
      @products # check all the checkboxes by default
      # or use Product.none for the opposite
    end
  end

  # ...
end

这是必需的,因为如果我们这样做,用户将无法重新添加项目@products = Product.where(id: params[:product_ids])

#index然后只需使用正确的复选框创建一个提交给您的操作的表单:

# Use `form_tag` instead for pre Rails 5 apps
= form_with(url: products_path, method: :get, local: true) do |form|
  %table.table
    %thead
      %tr
        %th Select
        %th Id
        %th Short description

    %tbody
      - @products.each do |product|
        %tr
          %td
            = check_box_tag('product_ids[]', product.id, @selected_products.include?(product))
          %td
          %td= product.id
          %td= product.short_description
  = form.submit('Filter products')

# this is just for demonstration
%h3 Selected products
- @selected_products.each do |p|
  %ul
    %li= p.short_description

推荐阅读