ruby-on-rails - Rails Arel_table 通过范围连接多个表
问题描述
我正在按角色在页面上进行过滤。因此,如果用户是 super_admin,则通过两个表显示角色匹配的所有其他内容。
用户示例:
- 用户:约翰史密斯
- 角色:太平洋西北地区
区域示例:
- 地区:太平洋西北地区
- 地点:西雅图、波特兰、博伊西
如果 John 登录到查看事件,他应该只看到位置在区域内的那些事件。所以说波特兰有一个事件,然后约翰会看到它。
用户 has_many 角色,区域 has_many 位置。事件 belongs_to 位置和区域,但可选。
现在这适用于将用户的角色连接到区域:
scope :for_user, lambda { |user|
if user.super_admin?
self
else
joins(:region)
.where(Region.arel_table[:name].matches("%#{user&.role&.name}%"))
end
}
所以 Location.name,Location.region_id = Region.id,Region.name = Role.name,Role.id = User.role_id。
我想我可以尝试类似的东西:
joins(:location)
.where(Location.arel_table[:region_id]).matches("%#{region.id}")
.joins(:region)
.where(Region.arel_table[:name].matches("%#{user&.role&.name}%"))
然而,这给出了:
不支持的参数类型:#
因此,鉴于可排序表具有位置和区域。如何根据与位置名称匹配的用户角色进行过滤?
编辑:
我想我可以用以下方式切换它:
region = Region.find_by(name: user&.role&.name)
if region.present?
joins(:location)
.where(location_id: region.location_ids)
end
然而,这显示了所有位置。我觉得它有点接近。所以我尝试了:
region = Region.find_by(name: user&.role&.name)
if region.present?
location = region.where(location_id: region.location_ids)
return true if location.present?
end
那失败了,所以我尝试了:
region = Region.find_by(name: user&.role&.name)
list_locations = []
Location.all.each.do |loc|
list_locations << loc.name if loc.region_id == region.id && region.present?
end
self if list_location.present?
这最终只是显示了一切。
解决方案
将其留在这里以防它对某人有帮助:
region = Region.find_by(name: user&.role&.name)
if region.present?
joins(:location)
.where(location_id: region.location_ids)
end
这实际上奏效了。我更新了我的视图以显示 location&.region&.name 并注意到它正在过滤,我只是有很多页面,它似乎无法正常工作。
推荐阅读
- reactjs - 权限不足:通过管理员登录时,请求在 google 目录 API 中的身份验证范围不足
- google-drive-api - G Suite:Google 群组可以成为云端硬盘中文件夹的所有者吗?
- javascript - 以编程方式在 edgeSDK 微服务的 http 请求中包含 curl 请求正文
- mongodb - 在填充字段猫鼬中过滤结果
- android - 适用于 Ionic 4 Android 和 IOS 的简易分析工具
- c# - Unity - 如何通过碰撞摧毁我的玩家?
- c - 如何在 CLion IDE 中做 EOF?
- python - 如何查看和自定义 Python 定义函数的源代码;描述、偏斜和峰度定义?
- excel - 使用 VBA 的函数
- javascript - Arduino websocket 需要使用 6 年前制作的节点“express”和“ws”进行更新