【问题标题】:Active Record multiple condition on a single field单个字段上的 Active Record 多个条件
【发布时间】:2016-08-24 08:59:26
【问题描述】:

我有以下模型关联:

class PartOfSpeech < ActiveRecord::Base
  has_many :part_of_speech_words
  has_many :words, through: :part_of_speech_words
end

class Word < ActiveRecord::Base
  has_many :part_of_speech_words
  has_many :part_of_speeches, through: :part_of_speech_words
end

class PartOfSpeechWord < ActiveRecord::Base
  belongs_to :part_of_speech
  belongs_to :word
end

我给了一组part_of_speech_ids 说[1,2,3]。有了这些关联,我必须找到包含所有这些 part_of_speeches 的所有单词。必须显示带有part_of_speech_ids [1,2,3,4] 的单词,但不能出现仅带有 [1,2] 的单词。

使用 IN 查询不会给出正确的结果,因为它执行 OR 操作。我想要对数组元素执行 AND 的东西。

请帮忙。

【问题讨论】:

标签: ruby-on-rails postgresql activerecord


【解决方案1】:

鉴于您的连接表中有 word_idpart_of_speech_id 的唯一索引,您可以只计算数学记录:

word_ids = PartOfSpeechWord.
  select('min(word_id) AS word_id').
  where(part_of_speech_id: part_of_speech_ids).
  group_by(:part_of_speech_id).
  having('COUNT(part_of_speech_id) >= ?', part_of_speech_ids.size).
  map { |x| x['word_id'] }

word = Word.where(id: word_ids)

【讨论】:

  • 当我的 part_of_speech_ids 是 [1,2,3] 时,有没有办法排序匹配 [1,2,3]、然后是 [1,2] 和最后一个 [1] 的结果。我知道这不是我之前的要求。但也需要在逻辑中添加这个
  • 例如,您可以运行一系列查询。但是引入某种缓存听起来更容易——您可以将part_of_speech_ids 数组属性添加到Word 模型,并在需要时更新它以缓存相关记录的ID(after_touch 回调在这里会有所帮助)。然后只需查询该属性。
猜你喜欢
  • 1970-01-01
  • 2022-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
  • 2016-05-21
  • 2017-06-15
相关资源
最近更新 更多