Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

validate parent model (See related posts)

Validate a parent model in child model
based on a post at http://www.railsweenie.com/forums/1/topics/439
question : can this be improvised?

Book (parent)
class Book < ActiveRecord::Base
  has_many :pages
end


Pages (children)
class Pages < ActiveRecord::Base
  belongs_to :book
  
  validates_presence_of :page_id # this is not enough, anything can go in this field

  # we check if the parent object is valid or not
  validate do |page|
   if page.blank?
     unless page.book(true)
       errors.add(:page_id, "must be a valid Book id")
     end
   end
  end

end


Comments on this post

seancribbs posts on May 12, 2007 at 12:50
Why not just validates_associated?
edxerx posts on May 17, 2007 at 01:51
based on http://www.railsweenie.com/forums/1/topics/439 since I had the same problem

validates_associated will not check on referential integrity. the above code will check for referential integrity.

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts