![](/img/trans.png)
[英]Rails 3 ActiveRecord Query, return all records of a model and include a count of associated records in a single query
[英]Rails: Return Records Where Array of IDs for Associated Model All Exist
所以我有一個進球模型,每個進球都有進球的時候滑冰。 我想將滑冰運動員的特定組合歸為目標的目標歸還。 關系看起來像這樣:
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語句(例如,查找具有OnIceSkaters的player_id 6382 AND 5635的目標)?
如果你寫兩個.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。
我不確定為什么Phlip的答案行不通(正如OP在評論中所說)。 如果您無法使其正常工作,那么您可以采用一種更為復雜且效率不高的方法(它使player_ids數量+ 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.