How to Add Errors to Rails Model?
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...
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.
1 Answer
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