【问题标题】:How to show error message on rails views?如何在 Rails 视图上显示错误消息?
【发布时间】:2015-06-27 19:46:46
【问题描述】:

我是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>
.....

模拟.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

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

提前致谢

【问题讨论】:

标签: ruby-on-rails ruby controller views


【解决方案1】:

关键是您正在使用模型表单,该表单显示 ActiveRecord 模型实例的属性。 create action of the controller 将负责一些验证(您可以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 返回false),则重新渲染new 视图。

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

然后在您的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 %>

【讨论】:

    【解决方案2】:

    这样做 -

     <%= 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 %> 
    

    【讨论】:

    • 你有一个额外的如果在这里:&lt;% if f.object.errors.each do |message| %&gt; 试图编辑,但它少于 6 个字符,所以我不会让我这样做。
    【解决方案3】:

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

    <%= error_messages_for :simulation %>
    

    检查http://apidock.com/rails/ActionView/Helpers/ActiveRecordHelper/error_messages_forerror_messages_for的完整语法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多