[英]validating array objects in active record
pls anyone help me to do validation in array of object...weightage is my field name..i just want to validate(presence and numericality) the weightage.but i could not get any validaation errors..i dont know at whivh place i did the mistake..if anyone knows the solution pls let me know 请任何人帮助我在对象数组中进行验证...重量是我的字段名称..我只想验证(存在和数值)重量。但是我没有得到任何验证错误..我不知道在哪里我做错了..如果有人知道解决方案,请让我知道
This is my view: 这是我的看法:
<tbody>
<% if @company_column_master != nil then
@company_column_master.each.with_index(0) do |assess,index| %>
<tr>
<td><%= index+1 %>
<%= hidden_field_tag :company_column_master_id ,assess.attributes["company_column_master_id"],name: 'cd_column_id[]' %>
<%= hidden_field_tag :data_element_id ,assess.attributes["data_element_id"],name: 'data_element_id[]' %>
<%= hidden_field_tag :display_order ,assess.attributes["display_order"],name: 'display_order[]' %>
</td>
<td><%= text_field_tag "display_name", assess.attributes["display_name"], name: 'display_name[]', size:50 ,:autocomplete => :off%></td>
<td><%= text_field_tag "weightage", assess.attributes["weightage"] ,name: 'weightage[]' ,:autocomplete => :off%></td> #getting values from db using array
<td class="text-center">
<%= check_box_tag('status'+index.to_s,'1',if (assess.attributes["status"] == 1) then true end, class: 'js-switch') %>
</td>
</tr>
<%end%>
<%= hidden_field_tag :phase_id ,@company_column_master[0].attributes["cd_phase_id"]%>
<%= hidden_field_tag :phase_detail_id ,@company_column_master[0].attributes["cd_phase_detail_id"]%>
<%end%>
</tbody>
This is my model part: 这是我的模型部分:
class CompanyColumnMaster < ActiveRecord::Base
validates :weightage, :presence => {:message => 'cannot be Blank!'}, :format => {:with => /\A[0-9]+\z/, message: "may only contain numbers."},
:length => {:maximum => 50, :message => 'Exceeds Maximum number of numbers.'}
validate :check_weightage
def check_weightage
if weightage!=nil && weightage < 0
errors.add(:weightage, "should be greater than or equal to zero")
end
end
end
You are doing 2 thing at the same time - you use Rails' validates
and custom validate
. 您同时在做两件事-使用Rails的
validates
和custom validate
。 Choose one. 选一个。
In order to use custom validation you have to write the method (what you've done almost Ok): 为了使用自定义验证,您必须编写方法(您几乎已经完成了什么):
validate :check_weightage
def check_weightage
errors.add(:weightage, "should be greater than or equal to zero") unless (weightage && weightage >= 0 && weightage.is_a? Integer)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.