简体   繁体   English

Ruby on Rails中的错误消息

[英]Error messages in Ruby on Rails

I did a validates_presence_of fields to the comments in the guide . 我为指南中的注释添加了validates_presence_of字段。 How to display validation errors on the posts page. 如何在帖子页面上显示验证错误。 I know about render, but with render i need to send all variables that i'm using on posts page. 我知道渲染,但有渲染我需要发送我在帖子页面上使用的所有变量。 Am i right? 我对吗?

I don't believe a plugin is required. 我不相信插件是必需的。 The scaffold generator in Rails 3.x does it this way: Rails 3.x中的脚手架生成器就是这样做的:

<%= form_for(@model) do |f| %>
  <% if @model.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@model.errors.count, "error") %> prohibited this model from being saved:</h2>

      <ul>
      <% @model.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
<%# Rest of form... %>

If you are looking to show the messages in your view, like so: 如果您希望在视图中显示消息,请执行以下操作:

用于error_messages的Rails UI

This is what you want.. More info http://www.monochrome.co.uk/blog/2010/04/14/rails-3-error_messages-and-error_messages_for 这就是你想要的..更多信息http://www.monochrome.co.uk/blog/2010/04/14/rails-3-error_messages-and-error_messages_for

`rails plugin install git://github.com/rails/dynamic_form.git`

<%= form_for @supermoon do |f| %>
  <%= f.error_messages %>

Plugin not required in rails 2.3 (is required in 3.x) rails 2.3中不需要插件(3.x中需要插件)

您可以在访问这些验证错误(和他们的消息) @variable.errors.full_messages所看到这里

validates_presence_of has a :message argument to custom an error message. validates_presence_of有一个:message参数来自定义错误消息。

class Person < ActiveRecord::Base
    validates_presence_of :user_name, :message => 'My custom error message'
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM