【发布时间】:2019-04-11 14:58:57
【问题描述】:
我有一个投票系统。
基本上我有一个挑战,有很多挑战项目。每个挑战项目都有很多照片,人们必须对这些照片进行投票。所以我记录了这些属于照片的选票。每张选票都有一个识别选民的指纹。因此,通过指纹,我可以获得用户的所有选票。 现在:我必须以用户已经从给定挑战中投票的挑战项目数组的形式获取 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
通过投票获得挑战的照片。 但是现在我还需要从这些照片中检索挑战项目...
有什么提示吗?
【问题讨论】:
标签: ruby-on-rails activerecord