Ryan McCrary
Ryan McCrary

Reputation: 61

Rails scope where has_one relation has no relation

Trip.rb

class Trip < ActiveRecord::Base
  has_one :report
end

Report.rb

class Report < ActiveRecord::Base
  belongs_to :trip
  belongs_to :user
end

Trips exist first, and then need a report. When a report gets created, it gets a trip_id. The relation works in that the console Trip.report shows the correct report

I'm trying to figure out how (presumably in the Trip model) to get a list of Trips that do not have a report through the relation

This seems like it should be straightforward, but I'm getting the sense it may not be.

scope :need_report, -> { where(joins(:report)) }

will get me the trips that have reports, but I'm trying to return the opposite.

Not sure if I should:

  1. Return the opposite of the join
  2. Nest and update the report_id to the trip somehow so it is easy to call

Upvotes: 0

Views: 933

Answers (1)

Vasili
Vasili

Reputation: 905

You can do it this way (returns an array):

scope :no_report, -> { select { |trip| trip.report.blank? } }

It's also possible to get an ActiveRecord::Relation:

scope :no_report, -> { includes(:report).where(report: { id: nil })

Upvotes: 4

Related Questions