繁体   English   中英

当前用户的Rails设置过滤器-连接关联问题

[英]Rails set filter by the current user - joins association issue

我有一个用于表单的过滤器,我只想显示那些具有与当前用户匹配的电子邮件的表单。

涉及的属性:用户的电子邮件,职业的收件人,地区名称

职位归属属于:region,我目前正在显示Region,并在其视图中显示以下内容:

-@careers.each do |career|
 th =career.region&.name

因此,逻辑是将current_user.email与所有Careers.recipienct进行比较,如果存在,则仅显示所表示的那些Region。

例如:

Region            | Career       | Recipients
Pacific Northwest | Data Analyst | john@doe.com, jill@excite.com

所以我知道它需要点击我的区域选择,如下所示:

= select_tag :region_id,
  options_from_collection_for_select(sort_region, :id, :name, params[:region_id]),
  include_blank: 'All Regions'

sort_region当前具有:

def sort_region
 Region.where.not(name: ['HQ', 'Canada'].sort_by(&:position)
end

所以我的想法是通过类似以下方式解决比较问题:

def user_region
 if current_user.super_admin?
  return sort_region
 else 
  arr = []
  Career.all.each do |emails|
   arr << emails.recipient
  end
  if arr.include?(current_user.email)
   return BLANK
  end
 end
end

空白是我卡住的地方。 我只想显示那些Career.recipient与current_user.email匹配的区域。

我为基本上我讨厌的回报写了以下内容

return Region.joins(:career).where("region.name = career.region&.name")

这实际上返回

无法加入“地区”加入名为“职业”的协会

我尝试时遇到同样的问题

return Region.joins(:career).where("careers.region_id = region.id")

我应该在这里使用正确的联接关联吗?

编辑:我想我可以解决返回的问题,如果我能弄清楚如何用电子邮件将第二个值推入数组。

所以像这样:

  arr = []
  Career.all.each do |emails|
    arr << emails.recipient
    arr << emails.region_id
  end
  if arr.include?(current_user.email)
    return region_id
  end

因此,这不会创建像我希望/想要的[[“ john@doe.com”,2],[“ jane@excite.com”,3]]配对,而是[[john@doe.com “,2,” jane@excite.com“,3]。 另外,我无法在region_id上返回。 因此,我只需要访问整数。

也许我应该创建所有项目的哈希,然后从那里提取?

另一个编辑:

尝试将条件放入迭代中。

arr = []
Career.all.each do |emails|
 if emails.recipient == current_user.email
  arr << emails.region_id
 end
end

但是,这显示了包含[1]的arr,它不是关联的region_id。

第三次编辑:

我最近的尝试是查看加入联接的过程,在该联接中,我简单地拔出了“职业接收者”等于current_user.email的那些区域。

Region.find(:all, joins: ' JOIN regions ON careers.region_id', conditions: "#{current_user.email} = careers.recipient")

找不到您要寻找的地区的结果。

Arel_table获胜

Region.joins(:careers).where(Career.arel_table[:recipient].matches("%#{current_user.email}%"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM