加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Active在单个字段上记录多个条件

发布时间:2020-12-17 01:56:55 所属栏目:百科 来源:网络整理
导读:我有以下模型关联: class PartOfSpeech ActiveRecord::Base has_many :part_of_speech_words has_many :words,through: :part_of_speech_wordsendclass Word ActiveRecord::Base has_many :part_of_speech_words has_many :part_of_speeches,through: :part
我有以下模型关联:

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,3,4]的单词,但不能只显示[1,2].

使用IN查询将无法在执行OR运算时给出正确的结果.我想要在数组元素上执行AND的东西.

请帮忙.

解决方法

鉴于您在连接表中有word_id和part_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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读