【发布时间】:2011-05-17 14:21:53
【问题描述】:
我怎样才能做到至少需要两个选项记录才能提交产品?
class Product < ActiveRecord::Base
belongs_to :user
has_many :options, :dependent => :destroy
accepts_nested_attributes_for :options, :allow_destroy => :true, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
validates_presence_of :user_id, :created_at
validates :description, :presence => true, :length => {:minimum => 0, :maximum => 500}
end
class Option < ActiveRecord::Base
belongs_to :product
validates :name, :length => {:minimum => 0, :maximum => 60}
end
【问题讨论】:
-
使用自定义验证应该非常简单。类似
self.errors.add_to_base("Two options are required") unless self.options.length >= 2 -
如果您使用
accepts_nested_attributes_for和allow_destroy: true,那么您必须使用marked_for_destruction?和孩子关联来找到孩子的确切长度,因为从表单提交时可能有一些对象已经保存对象后标记为_destroy: true用于销毁。长度、尺寸和数量不适合这种情况。这个链接有完美的答案。 link
标签: ruby-on-rails validation activerecord associations