Nadav
Nadav

Reputation: 119

Rails 2.3.8: Validating an object before save shows previous references and not updated ones

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!

Upvotes: 3

Views: 537

Answers (1)

Pavling
Pavling

Reputation: 3963

This is a problem you can duplicate in the console:

b = Book.new
=> #<Book id:nil, etc...>
b.author_id = 1
=> 1
b.author
=> #<Author id:1, etc...>
b.author_id = 2
=> 2
b.author
=> #<Author id:1, etc...>

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:

b.author = nil
=> nil
b.author_id = 2
=> 2
b.author
=> #<Author id:2, etc...>

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

author = Author.find(self.author_id) if self.author_id_changed?

(sorry if that was a lot of rambling that essentially didn't answer your question ;-)

Upvotes: 2

Related Questions