我有两个模型 Project
和 'Task`,其中 project has_many tasks 和 task 属于 project
现在在我的 Task
模型中,我正在使用项目中的属性对字段进行验证
validates :effort, :inclusion => 1..(project.effort)
这会导致错误 method_missing: undefined method project
问题是,我如何在 Rails 3 中根据父属性的值 (Project.effort) 验证子属性 (Task.effort)?
最佳答案
我最终在回调中进行了验证,如果无效则抛出异常。唯一的缺点是 Controller 必须捕获异常。
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
关于validation - 验证 :inclusion in rails based on parent Model's attribute value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3664192/