teamyates
teamyates

Reputation: 434

How to select rows in table using checkboxes and pass as parameters to controller

I have a table which displays a list of items. I'm trying to be able to select a few of the items in this table and pass to my controller where I hope to only render the specifically selected items.

# '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)

As shown above it displays a table where the first column is a selected checkbox with its value being its corresponding product.id - I'm trying to pass an array of those id's selected into the parameters - i.e the array SELECTED_PRODUCT_IDS.

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

Above shows my controller getting access to this array. I've seen a few answers to similar questions suggesting to put this into a 'form_for' tag however all my attempts have doing this have so-far failed.

Would appreciate any help.

Upvotes: 1

Views: 1130

Answers (1)

max
max

Reputation: 102154

Start by creating a separate variable which contains the @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

This is needed since there would be no way for the user to re-add items if we did @products = Product.where(id: params[:product_ids]).

Then just create a form that submits to your #index action, with the correct check boxes:

# 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

Upvotes: 2

Related Questions