我有一个用于模型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)中至少选中了一个复选框。
发布评论