我有一个投票系统。
基本上我有一个挑战,有许多挑战项目。每个挑战项目都有很多照片,人们必须投票这些照片。所以我记录了这些属于照片的投票。每个投票都有一个识别选民的指纹。因此,使用指纹,我可以获得用户的所有投票。现在:我必须以用户已经从给定挑战中投票的挑战项目阵列的形式获得ID。
我传递了两个参数:指纹,我用来返回投票数组,以及挑战。
我有这些模特
class Challenge < ApplicationRecord
has_many :challenge_items
has_many :photos, :through => :challenge_items
belongs_to :season
end
class ChallengeItem < ApplicationRecord
belongs_to :challenge
has_many :photos
has_many :votes, :through => :photos
end
class Photo < ApplicationRecord
belongs_to :challenge_item
has_many :votes
end
class Vote < ApplicationRecord
belongs_to :photo
end
投票属于属于挑战的照片。
我需要构建最有效的查询,从投票数组返回挑战项ID数组。
belongs_to关联不能具有:through选项
现在我用
challenge_photo_ids = Challenge.find(params["challenge"]).photos.map(&:id)
获取挑战照片的ID
get_already_voted = Vote.where(voter_string: params["voter_string"]).map(&:photo_id)
从投票中获取照片的ID
@already_voted = challenge_photo_ids & get_already_voted
通过投票获得挑战的照片。但是现在从这些照片我还需要检索挑战项目......
任何提示?
我可能没有得到你想要的东西。不是这样的吗?鉴于votes_ids
ChallengeItem.joins(photos: :votes).
where(challenge_id: challenge_id, votes: {id: votes_ids}).
distinct.pluck(:id)
这是我从这句话I need to build the most efficient query that return me the challenge items id array from a vote array
得到的