Last active
May 29, 2021 19:27
-
-
Save stevepolitodesign/8a25fbc8f7d92199271a44291bca27a0 to your computer and use it in GitHub Desktop.
Avoid scopes that use find_by
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackoverflow.com/a/31329956