Ruby on rails 如何使用复选框选择表中的行并将其作为参数传递给控制器

Ruby on rails 如何使用复选框选择表中的行并将其作为参数传递给控制器,ruby-on-rails,Ruby On Rails,我有一个表,其中显示项目列表。我正在尝试选择此表中的一些项目,并将其传递给我的控制器,希望在那里仅呈现特定选择的项目 # 'products/index.html.haml' %table.table %thead %tr %th Select %th Id %th Short description %tbody - @products.each do |product| %tr %td

我有一个表,其中显示项目列表。我正在尝试选择此表中的一些项目,并将其传递给我的控制器,希望在那里仅呈现特定选择的项目

# '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的数组传递到参数中-即数组
选中的产品\u id

# 'controllers/product_controller.rb'
def index
   product_ids = params[:selected_form_datums]
   ...
上面显示了我的控制器正在访问此阵列。 我已经看到了一些类似问题的答案,建议将其放入“
表单”标签中,但迄今为止,我所有的尝试都失败了


非常感谢您的帮助。

首先创建一个单独的变量,其中包含
@所选的\u产品

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

您必须使用表格并提交该表格。另一种方法是一些javascript解决方案。
# 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