Validate a belongs to association in a build situation

烈酒焚心 提交于 2019-12-24 04:16:06

问题


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?


回答1:


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




回答2:


When validating a nested attribute, you should do the following validation :

 validates_associated   :mission


来源:https://stackoverflow.com/questions/2538376/validate-a-belongs-to-association-in-a-build-situation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!