首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails / ransack作用域以返回带有条件的多个子行的父行

Rails / ransack作用域以返回带有条件的多个子行的父行
EN

Stack Overflow用户
提问于 2020-10-05 12:25:48
回答 1查看 138关注 0票数 1

我使用rails (5.2.4.3)、ransack和postgres,并使用以下简化的db模式:

代码语言:javascript
复制
Buildings
- id

BuildingSegments
- id
- building_id
- name

多个建筑物段可以属于一个建筑物,但一个建筑物也可以有0个建筑物段。在我的数据库中,大约有800万栋大楼和1000万个建筑段。

我正在尝试创建两个查询/作用域,这些查询/作用域也可以链接:

  1. 返回所有没有任何提供ID的建筑物段的建筑物,我正在尝试将它安装到这样的范围中:Building.without_building_segments([1, 2])。因此,这可以返回没有任何建筑物段的建筑物,或者没有id 1或2的n个建筑物段。

  1. 返回每个提供的ID至少有一个建筑物段的所有建筑物。范围类似于:Building.with_building_segments([1, 2])。因此,这只能返回具有至少两个建筑段的建筑物,其中一个有id 1,另一个id 2。

我尝试过使用各种联接、ransack谓词和子查询,但都没有效果。

你怎么解决这个问题?

EN

回答 1

Stack Overflow用户

发布于 2022-08-11 18:00:29

所以这里的要点是你会想要使用一些可搜索的范围。基本上,这些只是普通的范围,你让洗劫意识到。

代码语言:javascript
复制
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
end
代码语言:javascript
复制
Building.ransack({ without_building_segments: true })
# => Building without any segments

Building.ransack({ with_building_segments: [1,2] })
# => Buildings that have segments of 1 and 2
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64208576

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档