【问题标题】:How to scope by associations如何按关联进行范围
【发布时间】:2016-02-24 08:26:16
【问题描述】:

我在使用 Rails 4 和 Postgres 进行查询时遇到问题。

我有一个有很多选项的对象。

我想创建一个范围以根据一组选项 id 选择对象。

类似:

scope :with_options, -> (option_ids) { joins(:options).where('options.id IN (?)', option_ids) }

但我不需要任何,我需要所有。

诶。

如果我选择了 ID 为 [2,3 ,4] 的选项,我想选择与所有这些选项 ID 相关的所有对象,而不仅仅是其中的一些。

我尝试使用包含操作检查 postgres_ext gem,但我无法让它与关联一起使用。

这是我的结构:

class MyObject < ActiveRecord::Base
  has_many :my_object_options
  has_many :options, through: :my_object_options
end

class MyObjectOption < ActiveRecord::Base
  belongs_to :my_object
  belongs_to :option
end

class Option < ActiveRecord::Base
  has_many :my_object_options
  has_many :my_object, through: :my_object_options
end

知道如何构建我的范围吗?

谢谢

编辑:

我写了一个快速测试,通过了 spickermann 解决方案。

我在这里粘贴测试的描述。

describe "#with_options" do
  context "passing 2 options" do
    context "a my_object associated with both" do
      it "should be included"
    end

    context "a my_object associated only with one of the two options" do
      it "should not be included"
    end

    context "a my_object associated with one of the two options and a third one" do
      it "should not be included"
    end
  end
end

【问题讨论】:

  • 你当前范围的结果是什么?
  • 我当前的范围给了我所有具有任何选项的对象。我只想拥有所有这些的。

标签: ruby-on-rails ruby postgresql activerecord scope


【解决方案1】:

尝试计算关联选项的数量并返回匹配项最少的选项:

scope :with_options, lambda { |option_ids|   
  joins(:options).
  where(options: {id: option_ids }).
  group('my_objects.id').
  having('COUNT(DISTINCT options.id) >= ?', option_ids.size)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 2015-07-15
    • 2013-06-09
    相关资源
    最近更新 更多