如何在 rails 视图中显示错误消息?

How to show error message on rails views?

我是 rails 的新手,想在 form 字段上应用验证。

myviewsnew.html.erb

<%= form_for :simulation, url: simulations_path do |f|  %>

<div class="form-group">
  <%= f.label :Row %>
  <div class="row">
    <div class="col-sm-2">
      <%= f.text_field :row, class: 'form-control' %>
    </div>
  </div>
</div>
.....

Simulation.rb

class Simulation < ActiveRecord::Base
 belongs_to :user
 validates :row, :inclusion => { :in => 1..25, :message => 'The row must be between 1 and 25' }
end

simulation_controller.rb

class SimulationsController < ApplicationController

  def index
    @simulations = Simulation.all
  end

  def new
  end

  def create
    @simulation = Simulation.new(simulation_params)
    @simulation.save
    redirect_to @simulation
  end

  private
   def simulation_params
   params.require(:simulation).permit(:row)
  end

我想检查模型 class 中 row 字段的整数范围,如果 return 不在该范围内则显示错误消息。我可以检查上面代码的范围,但无法 return 错误消息

提前致谢

您只需将此代码添加到视图文件 (myviewsnew.html.erb):

<%= error_messages_for :simulation %>

检查 http://apidock.com/rails/ActionView/Helpers/ActiveRecordHelper/error_messages_for

error_messages_for 的完整语法

关键是您使用的是模型表单,一种显示 ActiveRecord 模型实例属性的表单。 create action of the controller will take care of some validation (and you can add more validation).

控制器重新渲染new模型保存失败时的视图

像下面这样更改您的控制器:

def new
  @simulation = Simulation.new
end

def create
  @simulation = Simulation.new(simulation_params)
  if @simulation.save
    redirect_to action: 'index'
  else
    render 'new'
  end
end

当模型实例保存失败时(@simulation.save returns false),然后new视图被重新渲染。

new 视图显示来自未能保存的模型的错误消息

然后在您的 new 视图中,如果存在错误,您可以像下面那样打印它们。

<%= form_for @simulation, as: :simulation, url: simulations_path do |f|  %>
  <% if @simulation.errors.any? %>
    <ul>
    <% @simulation.errors.full_messages.each do |message| %>
      <li><%= message %></li>
    <% end %>
    </ul>
  <% end %>
  <div class="form-group">
    <%= f.label :Row %>
    <div class="row">
      <div class="col-sm-2">
        <%= f.text_field :row, class: 'form-control' %>
      </div>
    </div>
  </div>
<% end %>

这里的重要部分是您正在检查模型实例是否有任何错误,然后将它们打印出来:

<% if @simulation.errors.any? %>
  <%= @simulation.errors.full_messages %>
<% end %>

这样做 -

 <%= form_for :simulation, url: simulations_path do |f|  %>
    <% if f.object.errors.any? %>
      <ul>
        <% if f.object.errors.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    <% end %>

   ..........
 <% end %>