Validate a belongs to association in a build situation
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. 开发者_如何学PythonI'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?
When validating a nested attribute, you should do the following validation :
validates_associated :mission
Use following in Mission.rb
has_many :tasks
validates_associated :task
Task.rb
belongs_to :mission
in controller
@mission=Mission.new(params[:mission])
task= @mission.tasks.build(params[:task]) ###this is same as Task.new(:mission_id=>@mission.id)
if @mission.save #this will save only when mission as well as task are valids, also it will automatically assign mission_id to tasks table you have nothing to worry about it<br>
else
#your error code will be here.......
end
Ref:- http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html
精彩评论