【问题标题】:Active record efficient query to recreate a belongs_to through活动记录高效查询通过重新创建belongs_to
【发布时间】: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


    【解决方案1】:

    我可能没有得到你想要的。不是这样吗?鉴于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得到的

    【讨论】:

    • 是的...但是要获得 vote_ids 我需要使用 votes_ids = Vote.where(voter_string: "21e8177a963f0422cb12e9f452faf3c4").map(&amp;:id) 并且根据您的查询我有所有投票挑战项目的 ID,但我只需要属于给定的挑战项目挑战!所以你的查询没问题,但我需要添加另外两个查询...
    • 好吧,只需在带有挑战 id 的 where 中添加另一个子句
    • 使用 pluck,它更快:votes_ids = Vote.where(voter_string: "21e8177a963f0422cb12e9f452faf3c4").pluck(:id)
    • 另外,您不能将 voter_string 添加到我的查询中并完全避免此查询吗?
    • 类似ChallengeItem.joins(photos: :votes). where(challenge_id: challenge_id, votes: {voter_string:"21e8177a963f0422cb12e9f452faf3c4"}). distinct.pluck(:id)
    猜你喜欢
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 2013-01-14
    • 2022-07-26
    相关资源
    最近更新 更多