我使用rails (5.2.4.3)、ransack和postgres,并使用以下简化的db模式:
Buildings
- id
BuildingSegments
- id
- building_id
- name多个建筑物段可以属于一个建筑物,但一个建筑物也可以有0个建筑物段。在我的数据库中,大约有800万栋大楼和1000万个建筑段。
我正在尝试创建两个查询/作用域,这些查询/作用域也可以链接:
Building.without_building_segments([1, 2])。因此,这可以返回没有任何建筑物段的建筑物,或者没有id 1或2的n个建筑物段。Building.with_building_segments([1, 2])。因此,这只能返回具有至少两个建筑段的建筑物,其中一个有id 1,另一个id 2。。
我尝试过使用各种联接、ransack谓词和子查询,但都没有效果。
你怎么解决这个问题?
发布于 2022-08-11 18:00:29
所以这里的要点是你会想要使用一些可搜索的范围。基本上,这些只是普通的范围,你让洗劫意识到。
class Building < ActiveRecord
# A set of ransackable scopes.
#https://activerecord-hackery.github.io/ransack/going-further/other-notes/#using-scopesclass-methods
# @param [Object] auth_object Auth object from Ransack/Devise
# @return [Array] An array of scopes that are class methods.
def self.ransackable_scopes(auth_object = nil)
%i(without_building_segments with_building_segments)
end
# Scope to only get buildings without segments.
# @return [ActiveRecord::Relation]
def self.without_building_segments
includes(:building_segments).where(building_segments: { id: nil })
end
# Scope to only get buildings with segments of ids
# @param [Array] ids array of building segment ids
# @return [ActiveRecord::Relation]
def self.with_building_segments(ids)
includes(:building_segments).where(building_segments: { id: ids })
end
endBuilding.ransack({ without_building_segments: true })
# => Building without any segments
Building.ransack({ with_building_segments: [1,2] })
# => Buildings that have segments of 1 and 2https://stackoverflow.com/questions/64208576
复制相似问题