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

5

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
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest