我有以下自定义验证:
def city_presence
if city_id.blank? && city_out_state.blank?
errors.add([:city_id, :city_out_state], "A City must be present")
throw(:abort)
end
end
它出错了,但它试图做的是:
city_id
和city_out_state
是否都为空
有一种简单的方法吗?
答案 0 :(得分:0)
我找到了一个有效的解决方案:
def city_presence
if city_id.blank? && city_out_state.blank?
errors.add(:city_id, "A City must be present")
errors.add(:city_out_state, "")
end
end
这是错误的部分。关键是,如果错误消息不是li
,则错误消息不会生成present?
:
<% if object && object.errors.any? %>
<div class="alert alert-danger">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<p><%= pluralize(object.errors.size, "error") %> prohibited this record from being saved</p>
<p>There were problems with the following fields:</p>
<ul>
<% object.errors.each do |attr, message| %>
<% if message.present? %>
<li>
<%= message %>
</li>
<% end %>
<% end %>
</ul>
</div>
<% end %>