我有一个显示项目列表的表格。我试图能够选择此表中的一些项目,并将其传递给我的控制器,我希望在该控制器中仅呈现特定选择的项目。
# '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的数组传递给参数-即数组{ {1}}。
SELECTED_PRODUCT_IDS
上图显示我的控制器可以访问此阵列。
我已经看到了一些类似问题的答案,建议将其放入'# 'controllers/product_controller.rb'
def index
product_ids = params[:selected_form_datums]
...
'标签中,但是到目前为止,我所做的所有尝试都失败了。
不胜感激。
答案 0 :(得分: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