Validate a belongs to association in a build situation.

Posted by Victor Martins on Stack Overflow See other posts from Stack Overflow or by Victor Martins
Published on 2010-03-29T13:56:45Z Indexed on 2010/03/29 14:43 UTC
Read the original article Hit count: 440

I have a Mission model that has_many Task, and the Task belongs_to Mission

For security I've made this validation on the Task Model:

  validates_presence_of :mission_id
  validates_numericality_of :mission_id

But the problem is that when create a Mission and add tasks like this:

 @mission.tasks.build

The validation returns error, because the mission id on the task is null ( the mission wasn't yet created )

If I delete the validation, the Mission and Task is created successfuly, but how can I keep the validation and still have this work? I could do a callback after the save, but I don't think that's right, because I don't want to save Tasks without a mission_id.

P.S. I'm hidding my mission field on the form. If I have it visible, it will show the currect mission and everything is ok. But if I hidde it the error happens.

<%=  f.hidden_field :mission, :label => "Missão" %>

Is the form reseting the attributes given by the controller on the new action?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about belongs-to