Rendering validation errors in Ruby on Rails

hitesh israni picture hitesh israni · May 10, 2012 · Viewed 18.2k times · Source

In a model say Task, I have following validation

 validates_presence_of :subject, :project, :user, :status

How do I render error messages for these validations using some other controller.

Inside CustomController I am using,

Task.create(hash)

passing nil values in hash gives following error,

 ActiveRecord::RecordInvalid in CustomController#create

 Validation failed: Subject can't be blank

Code in the controller's create action

@task = Task.create(hash)
if @task.valid?
   flash[:notice] = l(:notice_successful_update)
else
    flash[:error] = "<ul>" + @task.errors.full_messages.map{|o| "<li>" + o + "</li>" }.join("") + "</ul>"
end
redirect_to :back

How to render error messages to user.

Task model is already built and it renders proper messages. i want to use its functionalities from a plugin.

Answer

stellard picture stellard · May 10, 2012

This should work

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

      <ul>
      <% @task.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>