accepts_nested_attributes_for子关联验证失败accepts_nested_attributes_for

2023-09-08 15:43:00 作者:浑浑、噩噩的世界

我使用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