accepts_nested_attributes_for子关联验证失败 [英] accepts_nested_attributes_for child association validation failing

查看:250
本文介绍了accepts_nested_attributes_for子关联验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用accepts_nested_attributes_for在我的Rails的车型之一,并且我要救孩子创建父后。

I'm using accepts_nested_attributes_for in one of my Rails models, and I want to save the children after creating the parent.

形式的作品完美,但验证失败。为了简便起见想象一下以下内容:

The form works perfectly, but the validation is failing. For simplicity's sake imagine the following:

class Project < ActiveRecord::Base
  has_many :tasks
  accepts_nested_attributes_for :tasks
end

class Task < ActiveRecord::Base
  belongs_to :project

  validates_presence_of :project_id
  validates_associated :project
end

和我正在运行:

Project.create!(
  :name => 'Something',
  :task_attributes => [ { :name => '123' }, { :name => '456' } ]
)

一旦保存项目模型,验证失败的任务,因为他们没有一个PROJECT_ID(因为该项目尚未保存)。

Upon saving the project model, the validation is failing on the tasks because they don't have a project_id (since the project hasn't been saved).

好像Rails是按照以下方式:

It seems like Rails is following the pattern below:

  • 验证项目
  • 验证任务
  • 保存项目
  • 保存任务

该模式应该是:

  • 验证项目
  • 在通票:保存项目,继续...
  • 验证任务
    • 在通票:保存任务
    • 在失效:删除项目(?回滚也许)
    • Validate Project
    • On Pass: Save Project and continue...
    • Validate Tasks
      • On Pass: Save Tasks
      • On Fail: Delete Project (rollback maybe?)

      所以我的问题归结为:我怎样才能获得的Rails到父(项目)之后运行PROJECT_ID =(或项目=)方法和验证对儿童(任务)已保存,但不能保存父(项目)的模型,如果任何一个孩子(的任务)是无效的?

      So my question boils down to: How can I get Rails to run the project_id= (or project=) method and validation on the children (tasks) AFTER the parent (project) has been saved, but NOT save the parent (project) model if any child (task) is invalid?

      任何想法?

      推荐答案

      使用这个答案轨道2,否则请参阅下面的:inverse_of 答案

      Use this answer for Rails 2, otherwise see below for the :inverse_of answer

      您可以解决此通过的不可以检查的PROJECT_ID如果相关的项目是有效的。

      You can work around this by not checking for the project_id if the associated project is valid.

      
      class Task < ActiveRecord::Base
        belongs_to :project
      
        validates_presence_of :project_id, :unless => lambda {|task| task.project.try(:valid?)}
        validates_associated :project
      end
      

      这篇关于accepts_nested_attributes_for子关联验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆