Validating :inclusion in rails based on parent Model's attribute value

匿名 (未验证) 提交于 2019-12-03 07:50:05

问题:

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?

回答1:

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



回答2:

When this is intepreted the class doesn't know what the project object is. And such validates can't be added dynamically. You can do the following

    def valiate      unless (1..(project.effort)).member? effort        errors.add :effort, "must be within 1 to #{project.effort}"      end    end 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!