【问题标题】:Rails SQL query for many-to-many columnRails SQL查询多对多列
【发布时间】:2020-07-21 08:21:16
【问题描述】:

我有三个模型 - user journey_progressjourney 具有以下关联:

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

在我的端点中,我想为每个 journey 返回所有用户 journeyspercent_progress(它是 journey_progress 模块的列 - Journey_progress.percent_progress)。如何在一个查询中显示?

我所做的是:

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

【问题讨论】:

  • 但是为了什么?我想为每个旅程显示current_user.journeyspercent_progress
  • 对不起,我误解了这个问题。
  • current_user.journeys.includes(:journey_progresses).joins(:journey_progresses).each { |journey_progress| puts journey_progress.percent_progress }
  • 它给了NoMethodError: undefined method 'percent_progress' for #&lt;Journey:0x00007ffaf16ad300&gt;
  • Ups,对象应该是旅程的集合,所以一定是current_user.journeys.includes(:journey_progresses).joins(:journey_progresses).each { |journey| puts journey.journey_progresses.each { |journey_progress| puts journey_progress.percent_progress } }之类的东西。

标签: sql ruby-on-rails ruby psql


【解决方案1】:

您需要 JourneyProgress (percent_progress) 和 Journey 的数据。您希望总共进行 2 个查询(不是每个旅程一个)。

您最初的解决方案有点接近。你最后做了什么,在找到所有旅程进展后通过他们的 id 找到所有旅程是一个好主意,但你自己做没有意义。 Rails 已经内置了它。它叫includes

current_user.journey_progresses.includes(:journey)

现在,rails 将执行 2 次查询(有时甚至 1 次)并将旅程与每个进度相关联。现在,如果您只是在每个进度上调用journey,则不会进行其他查询。

由于您最终没有指定您想要的数据,我将仅演示如何获得包含 percent_progressJourney 的数组。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多