验证是否在Rails(非HABTM)中至少选中了一个复选框。

编程入门 行业动态 更新时间:2024-10-23 11:21:27
本文介绍了验证是否在Rails(非HABTM)中至少选中了一个复选框。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个用于模型Request的数据库表,该表具有一列为items的列。 Items是一个数组。当用户提交表单时,我需要进行验证,以确保在允许他们点击提交之前,数组不为空(即,至少检查了一项)。

I have a database table for the model Request that has a column that is items. Items is an array. When the user submits the form, I need a validation that ensures that the array is not empty (i.e., at least one item is checked) before they're allowed to hit submit.

我已经找到了如果item是属于Request的模型的方法,但是如果item只是Request中的一列,则不是。下面是我的最佳尝试,但是没有用,因为我收到一个错误消息您需要提供至少一个验证

I've found how to do this if item were a model that belonged to Request, but not if item is just a column within Request. Below is my best attempt, but it's not working, because I got an error `You need to supply at least one validation

模型代码

class Request < ActiveRecord::Base serialize :item validates :must_have_one_item def must_have_one_item for item in @request.items errors.add(:base, 'You must select at least one item') if request.item.blank? end end

查看表单代码

<%= f.check_box(:item, {:multiple => true}, "#{item}") %>

控制器代码

def create @requestrecord = Request.new(request_params) end private def request_params params.require(:request).permit({:item => []}) end

推荐答案

确定...发生的情况是,未选中复选框时,该复选框在数组中存储为 0,因此验证失败,因为该数组在技术上并不是空白。

Ok... what happens is that checkboxes, when unchecked, are stored in the array as "0", so the validation fails because the array isn't technically blank.

不检查任何内容时,存储的参数为 items = [ 0, 0, 0 , 0] 而不是 items = []

When nothing is checked, the paramaters that are stored is items = ["0", "0", "0", "0"] instead of items=[]

因此,它做了什么是这样的:

Therefore what did it was this:

def must_have_one_item errors.add(:items, 'You must select at least one item') unless self.items.detect { |i| i != "0" } end

更多推荐

验证是否在Rails(非HABTM)中至少选中了一个复选框。

本文发布于:2023-11-04 00:59:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556523.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:复选框   Rails   HABTM

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!