加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 每个字段下方的Rails显示表单错误

发布时间:2020-12-16 23:24:13 所属栏目:百科 来源:网络整理
导读:我有以下表格 %= form_for(@user) do |f| % % if @user.errors.any? % div id="error_explanation" h2%= pluralize(@user.errors.count,"error") % prohibited this user from being saved:/h2 ul % @user.errors.full_messages.each do |message| % li%= me
我有以下表格
<%= form_for(@user) do |f| %>
  <% if @user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@user.errors.count,"error") %> prohibited this user from being saved:</h2>

      <ul>
      <% @user.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <%= @user.errors.messages[:name] %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :email %><br>
    <%= f.text_field :email %>
  </div>
  <div class="field">
    <%= f.label :password %><br>
    <%= f.password_field :password %>
  </div>
  <div class="field">
    <%= f.label :phone %><br>
    <%= f.text_field :phone %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

我想为它下面的每个字段显示表单错误,而不是顶部的所有字段.经过rails guide,但无法知道如何做到这一点.

解决方法

您可以编写帮助程序以返回任何对象的任何字段的错误消息

在/app/helpers/application_helper.rb中:

def show_errors(object,field_name)
  if object.errors.any?
    if !object.errors.messages[field_name].blank?
      object.errors.messages[field_name].join(",")
    end
  end
end

在视图文件中:

<div class="field">
  <%= f.label :name %><br>
  <%= f.text_field :name %>
  <p class='error'><%= show_errors(@user,:name) %></p>
</div>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读