Skip to content

Instantly share code, notes, and snippets.

@stevepolitodesign
Last active May 29, 2021 19:27
Show Gist options
  • Save stevepolitodesign/8a25fbc8f7d92199271a44291bca27a0 to your computer and use it in GitHub Desktop.
Save stevepolitodesign/8a25fbc8f7d92199271a44291bca27a0 to your computer and use it in GitHub Desktop.
Avoid scopes that use find_by
# BAD
# This scope will return an ActiveRecord::Relation if the first query returns nil
class Post < ApplicationRecord
scope :featured, -> { find_by(featured: true) }
end
# => Post.featured
# => Post Load (0.1ms) SELECT "posts".* FROM "posts" WHERE "posts"."featured" = ? LIMIT ? [["featured", 1], ["LIMIT", 1]]
# => Post Load (0.1ms) SELECT "posts".* FROM "posts" /* loading for inspect */ LIMIT ? [["LIMIT", 11]]
# => #<ActiveRecord::Relation [...]>
# GOOD
# This class method will respect the find_by query
class Post < ApplicationRecord
def self.featured
find_by(featured: true)
end
end
# => Post.featured
# => Post Load (0.1ms) SELECT "posts".* FROM "posts" WHERE "posts"."featured" = ? LIMIT ? [["featured", 1], ["LIMIT", 1]]
# => nil
@stevepolitodesign
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment