问题描述
我在我的一个 Rails 模型中使用了 accepts_nested_attributes_for,我想在创建父级后保存子级.
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:
- 验证项目
- 验证任务
- 保存项目
- 保存任务
模式应该是:
- 验证项目
- 通过:保存项目并继续...
- 验证任务
- 通过:保存任务
- 失败时:删除项目(可能回滚?)
所以我的问题归结为:在保存父(项目)后,如何让 Rails 运行 project_id=(或 project=)方法和对子(任务)的验证,但不保存父(项目)模型是否有任何子(任务)无效?
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?
有什么想法吗?
推荐答案
针对 Rails 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 子关联验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!