首页 > 解决方案 > 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?

这最终只是显示了一切。

标签: ruby-on-rails

解决方案


将其留在这里以防它对某人有帮助:

region = Region.find_by(name: user&.role&.name)
if region.present?
 joins(:location)
  .where(location_id: region.location_ids)
end

这实际上奏效了。我更新了我的视图以显示 location&.region&.name 并注意到它正在过滤,我只是有很多页面,它似乎无法正常工作。


推荐阅读