Validate Parent Model
Join the DZone community and get the full member experience.Join For Free
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 endPages (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
Opinions expressed by DZone contributors are their own.