【发布时间】:2019-10-08 01:22:17
【问题描述】:
我正在按角色对页面进行过滤。因此,如果用户是 super_admin,则通过两个表显示角色匹配的其他所有内容。
用户示例:
- 用户:约翰·史密斯
- 角色:太平洋西北地区
区域示例:
- 地区:太平洋西北地区
- 地点:西雅图、波特兰、博伊西
如果 John 登录查看事件,他应该只会看到位置在区域内的那些事件。所以说波特兰有一个活动,然后约翰会看到它。
用户有_many 角色,区域有_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