Question

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.

Was it helpful?

Solution

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

OTHER TIPS

If you're talking about showing errors on the edit-page (i.e.: in the form), then consider usage of the simple_form gem. It'll show errors for you without a line of coding. Just replace form_for with simple_form_for and the magic will begin...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top