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

ruby-on-rails – 如何在rails视图上显示错误消息?

发布时间:2020-12-17 03:42:03 所属栏目:百科 来源:网络整理
导读:我是rails的新手,想要在表单字段上应用验证. 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' %
我是rails的新手,想要在表单字段上应用验证.

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

我想检查模型类中行字段的整数范围,如果它不在范围内,则返回错误消息.我可以从上面的代码检查范围,但不能返回错误消息

提前致谢

解决方法

关键是您正在使用模型表单,该表单显示ActiveRecord模型实例的属性. create action of the controller将负责一些验证(你可以 add more validation).

当模型无法保存时,Controller会重新呈现新的View

如下更改您的控制器:

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)时,将重新呈现新视图.

新视图显示无法保存的模型的错误消息

然后在新视图中,如果存在错误,您可以像下面一样打印它们.

<%= form_for @simulation,as: :simulation,url: simulations_path do |f|  %>
  <% if @simulation.errors.any? %>
    <% @simulation.errors.full_messages.each do |message| %>
      <li><%= message %></li>
    <% end %>
  <% 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 %>

(编辑:李大同)

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

    推荐文章
      热点阅读