确保父模型是一个的has_many一样的:通过协会轨3.2 [英] Ensure parent models are the same for a has_many :through association in rails 3.2
问题描述
我有一个与产品
和文件<相关的
处
父模型/ code>通过的has_many
/ 模式belongs_to的
的关系。在产品
和文件
模型,然后通过的has_many互相关联:通过
通过关系 ProductDocuments
加入的模式。
I have a Department
parent model that is associated with a Product
and Document
model through a has_many
/ belongs_to
relationship. The Product
and Document
models are then associated to each other through a has_many :through
relationship via a ProductDocuments
join model.
作为协会的一部分,还有就是产品
和文件
车型具有相同的<$ C的要求$ C>部门时被互相关联父模型。
As part of the associations there is a requirement that the Product
and Document
models have the same Department
parent model when being associated to each other.
现在我做以下内容:
ProductDocumentsController < ApplicationController
...
def create
@product = Product.find(params[:product_document][:product_id])
@document = Document.find(params[:product_document][:document_id])
if @product.department.id == @document.department.id
...
end
end
...
end
这工作的,但是感觉效率不高,因为它引入了控制器有两个附加的数据库调用。
This works, however it feels inefficient as it introduces two addition database calls in the controller.
没有人知道的一种方法,这可以以更有效的方式来完成,或者通过模型中的验证?
Does anyone know of a way that this can be accomplished in a more efficient way, perhaps through a validation in the model?
任何帮助将大大AP preciated;谢谢!
Any help would be greatly appreciated; thank you!
推荐答案
下面是我的想法。获取铅笔,纸和我一起绘制=)。我已经结束了这样的事情。
Here are my thoughts. Get pencil, paper and draw with me =). I've ended up with something like this.
Department * * * Product
* *
* *
* *
Document * * * ProductDocument
这就是所谓的循环引用的。通常情况下它会导致像你这样的情况 - 其中的表可能无限多领域的平等复杂的验证。那么,我们如何解决这个问题?
And that is something called circular reference. Typically it leads to cases like yours - complex validations of field equality among possibly infinite number of tables. So, how do we fix it?
变种夫妇:
- 简单地打破环节之一。例如,
文件
将参照产品
孤单。 - 删除引用
处
来自产品
和文件
,并把它在其他地方。例如,进入ProductDocument
(但是,它会被重命名为更合适,因为它会加入三种型号的东西)。
- Simply break one of the links. For example,
Document
will reference toProduct
alone. - Remove references to
Department
from bothProduct
andDocument
, and put it somewhere else. For example, intoProductDocument
(however, it's going to be renamed to something more appropriate since it will join three models).
这就是我能说的现在。
这篇关于确保父模型是一个的has_many一样的:通过协会轨3.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!