问题是这样的:
- 我有一组记录:收据。我想以有效的方式获取与这些收据对象关联的项目的唯一列表。对于这种特定类型的问题,我在 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
可能吗?
以下内容看起来很有希望:但是我如何访问祖 parent 记录呢?无需迭代子记录并产生巨大的数据库开销?
Receipt.joins(消息: [对话::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 - 如何从子记录集合中获取曾祖 parent 记录集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61319030/