请任何人帮我做对象数组验证...权重是我的字段名称..我只想验证(存在和数字)权重。但我无法得到任何验证错误..我不知道在whivh地方,我做错了..如果有人知道解决方案请让我知道
这是我的观点:
<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>
这是我的模范部分:
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
答案 0 :(得分:2)
你正在做两件事 - 你使用Rails&#39; validates
和自定义validate
。选择一个。
为了使用自定义验证,你必须编写方法(你已经做了几乎好的):
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