Rails:返回记录关联模型的ID数组全部存在的记录

时间:2018-03-02 22:04:55

标签: ruby-on-rails ruby postgresql join

所以我有一个目标模型,每个目标都有滑冰者在得分时在冰上。我想返回目标滑冰者特定组合的目标。这种关系看起来像这样:

class Goal < ApplicationRecord
  has_many :on_ice_skaters
end

class OnIceSkater < ApplicationRecord
 belongs_to :goal
end

我一直在尝试通过.joins然后一个.where但它似乎返回目标,阵列中的任何玩家都存在,而不是当ALL存在时(每个OnIceSkater记录都有一个player_id):

player_ids = [6382,5635]
Goal.joins(:on_ice_skaters).where('on_ice_skaters.player_id' => player_ids)

想知道是否有办法将上述语句转换为功能上的AND语句(例如,使用player_id 6382和5635查找具有OnIceSkaters的目标)?

2 个答案:

答案 0 :(得分:0)

如果您连续写两个.where()子句,ActiveRecord AND将它们放在一起。所以试试这个:

player_ids = [6382,5635]
goals = Goal.joins(:on_ice_skaters)

player_ids.each do |player_id|
  goals = goals.where(on_ice_skaters: { player_id: player_id })
end

我冒昧地将你的字符串升级为哈希。它可能更准确,而且看起来更像是Railsey。

答案 1 :(得分:0)

我不确定为什么Phlip的答案不起作用(正如OP在评论中所说)。如果你不能使它工作,那么你有一个更复杂和更有效的方法(它使 player_id + 1 查询的数量):

player_ids = [6382,5635]

# All goal ids for player 6328 (first player in the array)
goal_ids = Goal.joins(:on_ice_skaters).where(on_ice_skaters: { player_id: player_ids[0] }).pluck(:id).uniq

player_ids.shift.each do |player_id|
  # Keep only goals in common for each other player
  goal_ids = goal_ids & Goal.joins(:on_ice_skaters).where(on_ice_skaters: { player_id: player_id }).pluck(:id).uniq
end

# Take these ids.
goals = Goal.where(id: goal_ids)