validation - 验证 :inclusion in rails based on parent Model's attribute value

标签 validation activerecord ruby-on-rails-3

我有两个模型 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/

相关文章:

Java 验证无法正常工作

json - Azure 逻辑应用 - 验证 JSON 文件中的内容

ruby-on-rails - 使用多个数据库测试 Rails 应用程序

ruby-on-rails-3 - Rails 3,RSpec 2.5 : Using should_receive or stub_chain with named scopes

javascript - 如何删除无法创建图表: can't acquire context from the given item error while using it with Ruby on Rails?

javascript - 嵌套 View 模型的 Knockout 验证

twitter-bootstrap - Bootstrap 电子邮件验证

mysql - ActiveRecord:从数据库中的mediumblob中提取并命名图像

php - ORM 查询结果 : Arrays vs Result handle wrapped in Iterator interface

ruby-on-rails-3 - 如何从祖先生成json树