Nested models and parent validation

馋奶兔 提交于 2019-11-27 17:23:49
John Douthat

This will probably work for you, but I have a feeling there's a much better answer out there. It sounds like a bug to me.

class Parent < ActiveRecord::Base
  validate :must_have_children

  def must_have_children
    if children.empty? || children.all?(&:marked_for_destruction?)
      errors.add(:base, 'Must have at least one child')
    end
  end
end

It's not a bug. Acording to the documentation

Validates that the specified attributes are not blank (as defined by Object#blank?)

and validates :children, :presence => true is just the the same. The documentation doesn't say what happens if you try to use it on an association. You should use custom validation using validate.

Using validates_presence_of on has_many association calls blank? on association children, which is an object of class Array. Since the blank? is not defined for an Array, it fires method_missing which is caught inside Rails. Usually it do what you wants but I found it fails in Rails 3.1rc and Ruby 1.8.7 in a really awful way: it silently reverts the changes of associated records. It took me a couple of hours to find out what's happening.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!