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.
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".
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.
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.
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).
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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With