【发布时间】:2020-07-21 08:21:16
【问题描述】:
我有三个模型 - 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
在我的端点中,我想为每个 journey 返回所有用户 journeys 和 percent_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.journeys和percent_progress -
对不起,我误解了这个问题。
-
current_user.journeys.includes(:journey_progresses).joins(:journey_progresses).each { |journey_progress| puts journey_progress.percent_progress } -
它给了
NoMethodError: undefined method 'percent_progress' for #<Journey:0x00007ffaf16ad300> -
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