Rails验证:设置两个无效字段的样式,但只列出一个错误消息

时间:2017-05-24 21:06:39

标签: ruby-on-rails ruby

我有以下自定义验证:

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_idcity_out_state是否都为空
    • 如果是这样,那么将这些字段的两个添加到错误哈希中,以便为表单上的两个字段提供无效样式,但只显示一个错误项目符号消息。

有一种简单的方法吗?

1 个答案:

答案 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">&times;</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 %>