Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering validation errors in Ruby on Rails

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.

like image 952
hitesh israni Avatar asked May 10 '12 10:05

hitesh israni


People also ask

How do I validate in Ruby on Rails?

This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with option. Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option. The default error message is "is invalid".

How does validate work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.

What is the difference between validate and validates in rails?

So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.

What is err validation?

Validations errors are errors when users do not respond to mandatory questions. A validation error occurs when you have validation/response checking turned on for one of the questions and the respondent fails to answer the question correctly (for numeric formatting , required response).


1 Answers

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 %>
like image 100
stellard Avatar answered Oct 04 '22 02:10

stellard