Hrishikesh Sardar
Hrishikesh Sardar

Reputation: 2917

show validation error message from rails model

Is it possible to show validation error messages from controller by making our method ? please check the code below

validate :validation
  def validation
    if self.RJan.nil? && self.RFeb.nil? && self.RMar.nil? && self.R1.nil?
      #How do write my error message here ?
    end
  end

and my form

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

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

Upvotes: 0

Views: 1506

Answers (1)

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

You can add errors to your instance using

self.errors.add(:base, "your message here")

You could put attributes name as symbol instead of :base or whatever you like.

In your case

if self.RJan.nil? && self.RFeb.nil? && self.RMar.nil? && self.R1.nil?
  self.errors.add(:base, "your message here")
end

Upvotes: 1

Related Questions