Rails的ActiveRecord的::有道验证presence的联想? [英] Rails ActiveRecord:: Proper way for validating presence on associations?
问题描述
我的模型之间的Rails的关联项目
和队列
。一个项目的has_many队列。队列必须有一个项目,因此对PROJECT_ID一个presence验证
I have a Rails association between models Project
and Queue
. A project has_many queues. A queue must have a project, and consequently has a presence validation on project_id
假设我想创建队列一个新的项目。举例来说,这样的事情:
Suppose I want to create a new project WITH queues. For example, something like this:
project = Project.new(valid: param, options: here)
project.queues << Queue.new(other_valid: param, options: here)
project.save!
的保存是要失败的,因为队列失败PROJECT_ID presence验证。
The save is going to fail because the queues fail the project_id presence validation.
我平常丑得到解决这个的方法是创建一个项目,然后加入队列,并包裹了一大堆的事务,因此如果任何部分的过程中失败,它会回退。 ......不知怎的,这似乎难看比它应该是。
My usual ugly way of getting around this is to create a project, then add queues, and wrap the whole lot in a transaction so that if any part of the process fails, it rolls back. ...Somehow that seems uglier than it should be.
那么,有没有击中presence验证创建一个新的项目队列的更优雅的方式,但仍然断言,这些队列必须有一个项目?
So, is there a more graceful way of creating queues on a new project without hitting the presence validation, but still assert that those queues must have a project?
干杯
推荐答案
尝试使用的您的队列协会建立的方法,像这样的:
Try to use the build method on your queues association, like this:
project = Project.new(valid: param, options: here)
project.queues.build(other_valid: param, options: here) //this will build the queue and set its project_id to your current project.
project.save!
只是要确保你的PROJECT_ID具有正确的价值,称 project.save之前
插入此行:!
project.queues.each do |queue|
puts queue.project_id
end
那么,什么是错的与你的code?
So what's wrong with your code?
project = Project.new(valid: param, options: here) //build a new project - this is not yet persisted, so your id column is nil
project.queues << Queue.new(other_valid: param, options: here) // this line tries to save the queue to the database, does not wait for you to call project.save!
project.save!
当您拨打:
project.queues << Queue.new(other_valid: param, options: here)`
Rails的尝试到新的队列保存到数据库中,但因为你的项目没有保存, queue.project_id
是零所以你排队验证失败。
Rails tries to save your new queue to the database, but since your project is not saved, queue.project_id
is nil so your queue validation fails.
如果您尝试从数据库中获取一个项目(一个持久的项目),您的code将工作没有错误。类似的事情
If you try something similar with a project fetched from the database (a persisted project), your code will work without errors.
如果你仍然想使用类似的东西,添加新的队列就可以了,这样才保存项目:
If you still want to use something similar, save the project before adding a new queue on it, like this:
project = Project.new(valid: param, options: here)
if project.save
project.queues << Queue.new(other_valid: param, options: here) //this guarantees that project_id exists
end
这篇关于Rails的ActiveRecord的::有道验证presence的联想?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!