【问题标题】:Ensure parent models are the same for a has_many :through association in rails 3.2确保 has_many 的父模型相同:通过 rails 3.2 中的关联
【发布时间】:2014-02-12 18:23:22
【问题描述】:

我有一个 Department 父模型,它通过 has_many / belongs_to 关系与 ProductDocument 模型相关联。然后ProductDocument 模型通过has_many :through 关系通过ProductDocuments 连接模型相互关联。

作为关联的一部分,要求ProductDocument 模型在相互关联时具有相同的Department 父模型。

现在我正在做以下事情:

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

这行得通,但是感觉效率很低,因为它在控制器中引入了两个额外的数据库调用。

有谁知道可以通过模型验证以更有效的方式完成此任务的方法?

任何帮助将不胜感激;谢谢!

【问题讨论】:

  • “产品和文档模型在相互关联时具有相同的产品父模型”。你的意思是“同一个部门”?
  • @marvelousNinja 我确实做到了,谢谢您指出。

标签: ruby-on-rails ruby-on-rails-3.2 associations


【解决方案1】:

这是我的想法。拿铅笔、纸和我一起画画=)。我最终得到了这样的结果。

Department * * * Product
*                   *
*                   *
*                   *
Document * * * ProductDocument

这就是所谓的循环引用。通常它会导致像你这样的情况 - 可能无限数量的表之间的字段相等的复杂验证。那么,我们该如何解决呢?

几个变种:​​

  1. 只需断开其中一个链接。例如,Document 将单独引用 Product
  2. ProductDocument 中删除对Department 的引用,并将其放在其他位置。例如,进入ProductDocument(但是,它将被重命名为更合适的名称,因为它将加入三个模型)。

我现在只能说这些了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2016-08-24
    相关资源
    最近更新 更多