Check: inclusion in rails based on the parent value of the model attribute

I have two models Projectand the "Task", where the project has_many tasks and tasks belongs to the project

Now in my model TaskI am performing a field check using attributes in the project

validates :effort, :inclusion => 1..(project.effort)

This results in an error. method_missing: undefined method project

The question is, how can I test a child attribute (Task.effort) based on the value of the parent attribute (Project.effort) in Rails 3?

+3
source share
2 answers

I ended up checking in the callback and threw an exception if it is not valid. The only drawback is that the controller must catch the exception.

UPDATE

rails 3.0: https://web.archive.org/web/20110928154550/http://zadasnotes.blogspot.com/2010/12/rails-3-validation-using-parent-models.html

+2

intetreted, , . .

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

Source: https://habr.com/ru/post/1763711/


All Articles