Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby includes with scope

In my Rails 6 app I've got model Journey with defined active scope:

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

  scope :active, -> { where(is_deleted: false) }
end

In my endpoint I want to show user journey_progress and for serializer journey itself. To do so I'm using below query which works well

      def query
        current_user.journey_progresses.includes(:journey)
      end

How to modify above query to show only active journeys? I tried to just add where to be like current_user.journey_progresses.includes(:journey).where(is_deleted: false) but I'm getting an error:

Caused by PG::UndefinedColumn: ERROR:  column journey_progresses.is_deleted does not exist

According to this answer I tried with current_user.journey_progresses.includes(:journey).where(journey: {is_deleted: false} ) but I'm getting another error:

Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "journey"

What is the right syntax for that sort of action?

like image 709
mr_muscle Avatar asked Apr 13 '26 23:04

mr_muscle


2 Answers

You can merge a scope of a joined model.

current_user.journey_progresses.joins(:journey).merge(Journey.active)

This is better than testing for the is_deleted boolean because in future, if the definition of what makes a journey active changes, you won't need to modify the above line.

like image 132
SteveTurczyn Avatar answered Apr 15 '26 13:04

SteveTurczyn


Can you try the following?

current_user
  .journey_progresses.
  .joins(:journey)
  .where("journeys.is_deleted = ?", false)
like image 26
Kumar Avatar answered Apr 15 '26 14:04

Kumar