【发布时间】: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