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

问题描述 投票:1回答:1

我有一个显示项目列表的表。我正在尝试能够选择此表中的一些项目并传递给我的控制器,我希望只渲染特定选定的项目。

# '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
1个回答
2
投票

首先创建一个包含@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
© www.soinside.com 2019 - 2024. All rights reserved.