Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add errors to Rails model?

Tags:

I tried to add an exception in the before_save method in a rails model, but in the view, no error message exists.

Model:

before_save do     doing_some_stuff     begin       File.open('some_file', 'w+') do |file|         if file.write(file_content)           return true         else           return false         end       end     rescue => e       self.errors.add(:base, e.message)        return false     end 

View:

<%= @model.errors.any? %> 

This is always false.

How do I add error messages to the model?

EDIT:

The problem was, I had a redirect after the update_attribute function instead of rendering the action again. Thx for help.

like image 940
SonIcco Avatar asked Jul 01 '13 18:07

SonIcco


People also ask

What is Activerecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

How do you handle exceptions in Rails?

Exception handling in Ruby on Rails is similar to exception handling in Ruby. Which means, we enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle.

What is Validates_presence_of?

validates_presence_of(*attr_names) public. Validates that the specified attributes are not blank (as defined by Object#blank?), and, if the attribute is an association, that the associated object is not marked for destruction. Happens by default on save.


1 Answers

You should be performing this on validation, not on before_save. By the time you get to the before_save callback, the record is assumed to be valid.

validate do   doing_some_stuff   begin     File.open(some_file, 'w+') do |file|       if !file.write(file_content)         self.errors.add(:base, "Unable to write #{some_file}")       end     end   rescue => e     self.errors.add(:base, e.message)   end end 
like image 90
Chris Heald Avatar answered Sep 16 '22 14:09

Chris Heald