Search code examples
ruby-on-rails-3validationactiverecordreload

How to retain validation error messages after reload?


I am running several validations in my foo model. Here is how I am handling the create and update actions:

if @foo.update_attributes(params[:foo])
  #party time   
else
  @foo.reload #here is the issue
  render :action => "new" #or edit
end

I have to reload the attributes because I am using the default form values to run unrelated javascript. The problem is that by reloading the attributes, I apparently lose @foo.errors. Is there a way that I can pass them to the new reloaded variable? I would prefer this over using javascript to prevent the bad form submission. Thanks!


Solution

  • The reload method is obviously not for that. You can: 1. define your method for reverting the values 2. save the errors and then re-assign 3. merge attributes to the @foo from freshly loaded instance.

    All of these solutions are very hackish and are not recommended. If I were you, I'd rethink the way things should work.