Word有一个自我联接表,word1 is related with word2, word3, word4
project1 has many words
并包含project1 has: word1, word2
我如何获得words
的所有相关word1
除了那些已经分配给project1的内容,在这种情况下' word2'
word1: word3, word4
的预期输出(以下是我所做的,是否有更好的解决方案?)
related = project.words.where(id: self.related_words.map(&:id)).map(&:id)
self.related_words.where.not(id: related)
答案 0 :(得分:2)
鉴于您当前的解决方案有效,我会使用pluck
related = project.words.where(id: self.related_words.pluck(:id)).pluck(:id)
self.related_words.where.not(id: related)
为什么呢?因为pluck
用作数据库查询,因此与Ruby map
相比更快,请参阅文档:http://apidock.com/rails/ActiveRecord/Calculations/pluck