25 Jul 2008, 15:35
Generic-user-small

Chris Koerner (2 posts)

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?

28 Jul 2008, 23:16
Ryan_bates_cropped_pragsmall

Ryan Bates (60 posts)

I think there’s a lot of improvements that can be made regarding how Rails handles validations across associations. This included.

Looks like your solution would work (if you do self[:book_id]=), but I like to keep validations outside of the accessor methods. This way I can provide a more descriptive error message if I need. A custom validation might look like this:

validate :book_must_exist

def book_must_exist
  errors.add(:book_id, "must point to an existing book") if book_id && book.nil?
end

Why doesn’t validates_associated do this? I don’t know, seems like it should.

29 Jul 2008, 18:07
Generic-user-small

Chris Koerner (2 posts)

Fixing validates_associated seems like a job for SUPER RYAN - PATCH SUBMITTER OF RAILS CORE!! For truth, justice, and the common rails developer!

:)

  You must be logged in to comment