Ask A Question


You’re not receiving notifications from this thread.

Understand Scope Returns Discussion

Discussion for Understand Scope Returns

Excellent episode Collin!

Another tip is you could keep the future_events scope returning a Relation. And possibly break the sorting out in case it’s used for other queries as your application grows.

class Event < ApplicationRecord
  scope :future_events, -> { where("start_time > ?", Time.current) }
  scope :newest_first, -> { order(start_time: :asc) }

  def self.first_future_event

Elaborating further on this theme of composable scopes, and being handy both for tests and for reporting, leaning on the predicate builder and a default parameter:

scope :future, ->(after = Time.current) { where.not(start_time: ..after) }

There’s also an argument for using a CurrentAttributes value for time, since application code depending directly on Time.current may fall into the trap of assuming it is the same value throughout a single request’s execution, when of course it may not be, leading to some really subtle intermittent bugs, especially at the cusp of midnight.


Very interesting episode, Collin! TIL you could get the path to the source of a method right from the console ✨


Thank you! Glad you enjoyed it and learned something new!!


amazing and wild

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 78,890+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2023 GoRails, LLC. All rights reserved.