There’s a form on my site allowing to update an object (i.e. Book).
The book contains the field author_id which references the Author class.
The form allows changing the author.
When saving the book, validations are run,
but when a certain validation calls self.author, it will receive the previous author and not the new one that was chosen.
To deal with this problem, I always have to start the validations with reloading the new author in the following way:
def some_validation
author = Author.find(self.author_id)
...
end
Why won’t the validation see the new author, and how can I make it see it,
without having to reload the new referenced object every time?
Thanks!
This is a problem you can duplicate in the console:
so… changing the association ID (which is what the form update_attributes does) doesn’t change the loaded associated object.
but, if you nullify the object first, the associated object does reload:
So you can (note the italics, because I don’t know what is the best solution) set the object to nil in the controller if the association id is in the params hash, or continue using your method, but add a guard to only reload if necessary
(sorry if that was a lot of rambling that essentially didn’t answer your question 😉