开发者

Error messages in Ruby on Rails

I did a validates_presen开发者_JAVA百科ce_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 in Ruby on Rails

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)


You can access these validation errors(and their messages) in the @variable.errors.full_messages as seen here.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜