验证:包括在轨基于父模型的属性值 [英] Validating :inclusion in rails based on parent Model's attribute value

查看:146
本文介绍了验证:包括在轨基于父模型的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个型号项目和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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆