It would seem that validates_associated would check to make sure that the value in a record’s foreign key field points to a valid entry in the associated table, yet it fails to do so. A case of a poorly named validation method or a bug, not sure which.
References : Docs on validation: http://rails-doc.org/rails/ActiveModel/Validations/ClassMethods/validates_associated Ticket on problem : http://dev.rubyonrails.org/ticket/5369
What would you recommend as the best way to ensure that when a record is created or updated, that any associates are actually valid?
Example Book, Page
Book has_many Pages Page belongs_to Book
Don’t save a page if it doesn’t point to a valid book.
One suggestion, override the foreign_key attribute method in the model:
Class Page < ActiveRecord
belongs_to :book validates_presence_of :book_id validates_associated :book
def book_id=(bid) book_id = bid if Book.find(bid) end ————————————————–
I ‘think’ that would work. Thoughts?