多对多列的rails sql查询

3gtaxfhh  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(248)

我有三个模型-
user journey_progress 以及 journey 具有以下关联:

class User < ApplicationRecord
  has_many :journey_progresses, dependent: :destroy
  has_many :journeys, through: :journey_progresses
end

class JourneyProgress < ApplicationRecord
  belongs_to :user
  belongs_to :journey
end

class Journey < ApplicationRecord
  has_many :users, through: :journey_progresses
  has_many :journey_progresses, dependent: :destroy

  validates :percent_progress, inclusion: 0.0..1.0
end

在我的端点中,我想返回所有用户 journeyspercent_progress (这是一列 journey_progress 模块-每个模块的行程(进度百分比) journey . 如何在一个查询中显示?
我所做的是:
current_user 我能做到: progress = current_user.journey_progresses 这给了我:

[46] pry(main)> progress = current_user.journey_progresses
  JourneyProgress Load (0.6ms)  SELECT "journey_progresses".* FROM "journey_progresses" WHERE "journey_progresses"."user_id" = $1  [["user_id", 1]]
=> [#<JourneyProgress:0x00007ffaf9b86cc0 id: 1, user_id: 1, journey_id: 2, percent_progress: 1.0, created_at: Mon, 20 Jul 2020 23:00:27 UTC +00:00, updated_at: Mon, 20 Jul 2020 23:08:58 UTC +00:00, started_at: nil, finished_at: Mon, 20 Jul 2020 23:08:58 UTC +00:00>]

现在我可以赶上旅行了:

Journey.where(id: progress.each { |progress| progress.journey_id })

但我不知道怎么展示 percent_progress 对于每个用户的旅程。

xzv2uavs

xzv2uavs1#

您需要来自journeyprogress的数据( percent_progress )和旅程。您希望总共进行2次查询(不是每次行程一次)。
你原来的解决方案有点接近。你最后所做的是,在找到所有的旅程进展之后,通过他们的id找到所有的旅程,这是一个好主意,但是你自己做没有意义。rails已经内置了它。它叫 includes .

current_user.journey_progresses.includes(:journey)

现在rails将执行2个查询(有时甚至是1个查询),并将旅程与每个进度相关联。如果你打电话来 journey 对于每个进度,将不进行任何其他查询。
因为您没有指定最终需要数据的方式,所以我将演示如何使用 percent_progress 以及 Journey 在里面。

current_user.journey_progresses.includes(:journey).map do |journey_progress|
  [journey_progress.percent_progress, journey_progress.journey]
end

相关问题