验证嵌套属性presence [英] Validate presence of nested attributes
问题描述
我如何验证模型具有使用嵌套的属性至少有一个关联的模型?这是推动我疯了,因为我相信,我失去了一些东西简单。例如,我想要求一个列表总是至少有一个任务。
How do I validate that a model has at least one associated model using nested attributes? This has been driving me crazy as I am sure that I am missing something simple. For example, I want to require that a List always has at least one Task.
class List < ActiveRecord::Base
has_many :tasks, :dependent => :destroy
accepts_nested_attributes_for :tasks, :allow_destroy => true
end
class Task < ActiveRecord::Base
belongs_to :list
end
我已经尝试了许多不同的选择。
I've tried many different options.
1 - 增加一个验证,以列表:
1- adding a validation to lists:
def validate
if self.tasks.length < 1
self.errors[:base] << "A list must have at least one task."
end
end
但这将仍然允许你删除删除任务清单的验证发生之前的任务被破坏时,由于一个现有列表中的所有任务。
but this will still allow you to delete all the tasks of an existing list since when deleting tasks the validation of list happens before the tasks are destroyed.
2 - 检查,看是否有任务不标记为破坏的before_save回调
2- checking to see if any tasks are not marked for destruction in a before_save callback
before_save :check_tasks
private
#look for any task which won't be deleted
def check_tasks
for t in self.tasks
return true if ! t.marked_for_destruction?
end
false
end
由于某种原因,我不能让它永远删除任务与任何遍历一个列表的任务。同样如此,如果我做此项检查在高清验证
,而不是回调
3,要求任务的presence validates_ presence_of:任务
,但是这一点,永远不会删除任何任务
3- requiring the presence of tasks validates_presence_of :tasks
, but with this it won't ever delete any tasks
推荐答案
我结束了扩大杂志的保存方法来解决这个问题。它的工作就像一个魅力。
I ended up extending Magazine's save method to get around the problem. It worked like a charm.
def save
saved = false
ActiveRecord::Base.transaction do
saved = super
if self.conditions.size < 1
saved = false
errors[:base] << "A rule must have at least one condition."
raise ActiveRecord::Rollback
end
end
saved
end
这篇关于验证嵌套属性presence的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!