What I am trying to accomplish is a simple "toggle" checkbox for On/Off for a view which contains records from a model.
I have attempted to look into a "hidden" value, but it doesn't appear to work as intended.
How to get blank checkboxes to pass as false to params
When I've added: <%= hidden_field_tag "category_ids[]", '' %>
I receive Couldn't find Category with 'category_name'=
when unchecking.
Essentially, the table is a Model.all
, but I want to be able to modify the key value on an is_active
column to true
or false
, depending on if the box is checked, or not. Currently, I can accomplish this for "checking" the box. But, not unchecking (passes null
). I am trying accomplish this is one swoop rather than making all my checkes, and another pass for my unchecked. And, also bypassing the show/edit process. The table size is rather small, so I am not concerned with latency.
I have attempted to search as much as I could, but am at a loss. With what I've found I can do one or the other, but not both unfortunately, and I would greatly appreciate any guidance.
My view:
<h4>Categories</h4>
<%= form_tag enable_categories_path, method: :put do |f| %>
<table id="myTable" class="table table-bordered table-striped">
<tr>
<th>Enable</th>
<th>Category Name</th>
<th>Active</th>
</tr>
<tbody>
<% @categories.each do |category| %>
<tr>
<td>
<%= check_box_tag "category_ids[]", category.id, category.is_active == 1 ? 'checked' : nil %>
</td>
<td><%= link_to category.category_name, category %></td>
<td><%= category.is_active == 1 ? 'Yes' : 'No' %></td>
</tr>
<% end %>
</tbody>
</table>
<%= render 'settings/button' %>
<% end %>
Here, the checkboxes are grabbing their state from the model itself for the corresponding record, so if no action is taken on the checkbox it remains the same (or passes state back)
My controller:
class CategoriesController < ApplicationController
before_action :set_category, only: [:show, :edit, :update]
def index
@categories = Category.all.order(:category_sort)
end
def show
@category = Category.find(params[:id])
end
def edit
end
def update
if @category.update(category_params)
redirect_to categories_path
else
render :edit
end
end
def enable
Category.update(params[:category_ids], params[:category_ids].map{ |e| {is_active: true} })
redirect_to categories_path
end
private
def set_category
@category = Category.find(params[:id])
end
def category_params
params[:category].permit(:id, :category_name, :is_active)
end
end
Currently, I'm only passing is_active: true, until I can figure a way to pass ALL checkbox states.
My model:
class Category < ActiveRecord::Base
self.table_name = 'categories'
has_many :metrics
end
My route:
resources :categories do
collection do
put :toggle
end
end
Everything appears to pass correctly for checked boxes. But, nothing appears in the logs for when something is unchecked.