squeel icon indicating copy to clipboard operation
squeel copied to clipboard

Accessing a records associations with a scope

Open simkessy opened this issue 10 years ago • 2 comments
trafficstars

I'm trying to use a scope to return records based on the value of a association column. I can't seem to figure it out unfortunately.

Basically each Availability is associated with a Venue, through a Facility Each Venue has a column called notice_time which is an integer. I'm trying to return Availabilities where the Venue it's associated with has a notice_time that is after the current time.

class Availability < ActiveRecord::Base
  belongs_to :facility
  has_one :venue, through: :facility

  scope :after_notice_time, -> {joins{venue}.where{start_time >= (self.venue.notice_time.hours.from_now)}}
end

simkessy avatar Nov 10 '15 02:11 simkessy

Note that things within where clauses are key paths, not model calls (so you can't use cute Rubyisms like hours.from_now on column values.

When you say notice_time is an integer - is it a timestamp or an interval? If it's an interval, you'll need to use the database interval functions to calculate if the interval has passed.

stephenprater avatar Dec 04 '15 01:12 stephenprater

You can use hours.from_now if you use it in a my{} block. Squeel will convert the time correctly for you.

mckinnsb avatar Feb 26 '16 14:02 mckinnsb