【发布时间】:2018-04-04 21:22:26
【问题描述】:
我想要完成的是一个简单的“切换”复选框,用于打开/关闭包含来自模型的记录的视图。
我试图查看一个“隐藏”值,但它似乎没有按预期工作。
How to get blank checkboxes to pass as false to params
当我添加时:<%= hidden_field_tag "category_ids[]", '' %>
取消选中时我收到Couldn't find Category with 'category_name'=。
本质上,该表是Model.all,但我希望能够将is_active 列上的键值修改为true 或false,具体取决于是否选中该框。目前,我可以通过“检查”框来完成此操作。但是,不要取消选中(通过null)。我正在努力实现这一目标,而不是让我所有的检查,以及我未检查的另一次通行证。而且,还绕过了显示/编辑过程。表比较小,所以我不关心延迟。
我已尽我所能搜索,但不知所措。根据我的发现,我可以做一个或另一个,但不幸的是不能两者都做,我将非常感谢任何指导。
我的看法:
<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 %>
这里,复选框从模型本身获取其状态以获取相应记录,因此如果未对复选框采取任何操作,则它保持不变(或将状态传回)
我的控制器:
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
目前,我只传递 is_active: true,直到我想办法传递所有复选框状态。
我的模特:
class Category < ActiveRecord::Base
self.table_name = 'categories'
has_many :metrics
end
我的路线:
resources :categories do
collection do
put :toggle
end
end
对于选中的复选框,一切似乎都正确通过。但是,未选中某些内容时,日志中不会出现任何内容。
【问题讨论】:
-
你能以某种方式实现collection_check_boxes吗? apidock.com/rails/v4.0.2/ActionView/Helpers/FormOptionsHelper/…
-
我相信collection_check_boxes 最适合关联。其中类别没有关联(至少在执行编辑的方式上)
-
你能明确传递
true/false作为复选框的值吗? -
我想我不清楚,
is_active列是布尔值吗?
标签: mysql ruby-on-rails ruby forms