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