gpt4 book ai didi

ruby-on-rails - 如何从子记录集合中获取曾祖父记录集合?

转载 作者:行者123 更新时间:2023-12-04 10:11:29 24 4
gpt4 key购买 nike

这是问题所在:

  • 我有一组记录,它们是:收据。我想以有效的方式获取与这些收据对象关联的唯一项目列表。对于这种特定类型的问题,我无法在 SO 上找到类似的问题/解决方案。

  • 这就是我要的:
    @projects = @receipts.getUniqueProjects()
    # Project.rb

    has_many :conversations

    # Conversation.rb

    has_many :messages
    belongs_to :project

    # Message.rb

    has_many :receipts
    belongs_to :conversation

    # Receipt.rb

    belongs_to :message

    是否可以?

    以下看起来很有希望:但是我如何访问祖父记录?不遍历子记录并产生巨大的数据库开销?
    Receipt.joins(message: [conversation: :project])
    任何指针将不胜感激。

    这是我使用的:
    @projects = Project.joins(conversations: {messages: :receipts} ).where(receipts: [1,2,3,4]).uniq

    谢谢 Vasilisa - 感谢您的远见,看到这是一个 XY 问题。

    最佳答案

    您可以使用 has_many :through关联,通过嵌套设置“快捷方式”很有用 has_many协会。

    # Project.rb

    has_many :conversations
    has_many :messages, through: :conversations
    has_many :receipts, through: :messages

    # Conversation.rb

    has_many :messages
    belongs_to :project

    # Message.rb

    has_many :receipts
    belongs_to :conversation

    # Receipt.rb

    belongs_to :message

    在这种情况下,您可以轻松加入他们并使用 distinct只获得 uniq 项目
    Project.joins(:receipts).distinct.where(receipts: { id: [1, 2, 3] })

    关于ruby-on-rails - 如何从子记录集合中获取曾祖父记录集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61319030/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com