views:

176

answers:

2

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?

A: 

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
Rishav Rastogi
this is assuming you have a relationship b/w Task and Project model, each task effort should be within the range of its project's effort
Rishav Rastogi
I finally got a chance to try it out. Somehow your suggestion did not work for me. It was still not validating the change. 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.
Zaid Zawaideh
A: 

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.

Zaid Zawaideh