开发者

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

I have two models Project and 'Task` where project 开发者_StackOverflowhas_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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜