验证:包括在轨基于父模型的属性值 [英] Validating :inclusion in rails based on parent Model's attribute value
问题描述
我有两个型号项目
和Task`中,项目的has_many任务和任务属于项目
现在在我的工作
模型我使用属性的项目做验证一个字段
验证:努力,:包括=> 1 ..(project.effort)
这导致一个错误的method_missing:未定义的方法项目
问题是,我如何可以验证基于父母的属性值(Project.effort)子属性(Task.effort)在Rails的3?
解决方案最后我做一个回调验证,如果它是无效抛出一个异常
更新
基于轨道3.0定制的验证有一个更好的解决方案: <一href="https://web.archive.org/web/20110928154550/http://zadasnotes.blogspot.com/2010/12/rails-3-validation-using-parent-models.html" rel="nofollow">https://web.archive.org/web/20110928154550/http://zadasnotes.blogspot.com/2010/12/rails-3-validation-using-parent-models.html
I have two models Project
and 'Task` where project has_many tasks and task belongs to project
Now in my Task
model I am doing validation on a field using attributes in the project
validates :effort, :inclusion => 1..(project.effort)
This results in an error method_missing: undefined method project
Question is, how can I validate a child attribute (Task.effort) based on a parent's attribute's value (Project.effort) in Rails 3?
I ended up doing the validation in a callback and throwing an exception if it is not valid. The only drawback is that the controller has to catch the exception.
UPDATE
A better solution based on rails 3.0 custom validators: https://web.archive.org/web/20110928154550/http://zadasnotes.blogspot.com/2010/12/rails-3-validation-using-parent-models.html
这篇关于验证:包括在轨基于父模型的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!