我有一个投票系统。
基本上,我有一个挑战,有很多挑战项目。每个挑战项目都有很多照片,人们必须对这些照片进行投票。因此,我记录了属于照片的这些票。每个投票都有一个可识别投票者的指纹。因此,有了指纹,我可以拥有用户的所有票。 现在:我必须以用户已经从给定挑战中投票的挑战项目的数组形式获取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
通过投票获取挑战的照片。 但是现在,从这些照片中,我还需要检索挑战项目...
有任何提示吗?
答案 0 :(得分:0)
我可能没有得到您想要的。这样不是吗给定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