如何在Rails视图上显示错误消息? [英] How to show error message on rails views?

查看:93
本文介绍了如何在Rails视图上显示错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am newbie in rails and want to apply validation on form fields.

myviewsnew.html.erb

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

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

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 字段的整数范围,如果不在范围内,则返回错误消息。我可以检查上述代码的范围,但无法返回错误消息

I want to check the integer range of row field in model class and return the error message if it's not in the range. I can check the range from above code but not able to return the error message

预先感谢

推荐答案

关键是您使用的是模型表单,该表单显示ActiveRecord模型实例的属性。 控制器的创建动作将负责一些验证(您可以添加更多验证)。

The key is that you are using a model form, a form that displays the attributes for an instance of an ActiveRecord model. The create action of the controller will take care of some validation (and you can add more validation).

按如下所示更改控制器:

Change your controller like below:

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 视图。

When the model instance fails to save (@simulation.save returns false), then the new view is re-rendered.

然后使用在您的新建视图中,如果存在错误,则可以像下面一样打印它们。

Then within your new view, if there exists an error, you can print them all like below.

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

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

The important part here is that you're checking whether the model instance has any errors and then printing them out:

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

这篇关于如何在Rails视图上显示错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆