在构建情况下验证所属关联
我有一个具有多个任务的任务模型,并且该任务属于任务
为了安全起见,我对任务模型进行了此验证:
validates_presence_of :mission_id
validates_numericality_of :mission_id
但问题是,当创建任务并添加这样的任务时:
@mission.tasks.build
验证返回错误,因为任务任务的 id 为空(任务尚未创建)
如果我删除验证,任务和任务将成功创建,但如何保留验证并仍然进行这项工作? 我可以在保存后进行回调,但我认为这是不对的,因为我不想在没有 Mission_id 的情况下保存任务。
聚苯乙烯 我在表格上隐藏了我的任务字段。如果我让它可见,它将显示当前的任务并且一切正常。但如果我隐藏它,就会发生错误。
<%= f.hidden_field :mission, :label => "Missão" %>
表单是否会重置控制器在新操作上给出的属性?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
验证嵌套属性时,您应该执行以下验证:
When validating a nested attribute, you should do the following validation :
中使用以下内容
参考中的 Mission.rb Task.rb
在控制器
:- http:// api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html
Use following in Mission.rb
Task.rb
in controller
Ref:- http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html