Active record of several conditions in one field

I have the following model associations:

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

I gave with a set to part_of_speech_idssay [1,2,3]. With these associations, I have to find all the words that have all these part_of_speeches in it. The word with part_of_speech_ids[1,2,3,4] should be displayed, but not the word only with [1,2].

A query with IN will not produce the correct result because it is performing an OR operation . I want something that does AND for array elements.

Please, help.

+4
source share
1 answer

, word_id part_of_speech_id , mathching:

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)
0

Source: https://habr.com/ru/post/1652301/


All Articles