Reputation: 61
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:
Upvotes: 0
Views: 933
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