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
%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
' 标签中,但是到目前为止,我所做的所有尝试都失败了。
将不胜感激任何帮助。
解决方案
首先创建一个包含@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
推荐阅读
- assembly - 如何在 IBMPC BIOS 图形模式 16 (INT 10H/AX=0010H) 中启用文本光标?
- visual-c++ - 如何绘制这个圆而不是 Bresenham 的圆算法
- c++ - LINUX 上的 Node.JS 原生插件
- sharepoint - 将模板从一个 SharePoint 网站复制到另一个
- php - 基于 php 版本在 ruby 上创建 post 请求
- excel - 识别excel中两个文本字符串之间的不同值
- angular - 调用异步函数并返回数组中的值
- excel - 第一次单击时命令按钮不起作用
- amazon-web-services - 如何在 EC2 实例上为来自托管 s3 存储桶的请求创建入站规则
- javascript - 如果对象中有重复值,则 JavaScript 求和值