简体   繁体   中英

Error messages in Ruby on Rails

I did a validates_presence_of fields to the comments in the guide . 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:

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

`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)

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

validates_presence_of has a :message argument to custom an error message.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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