Skip to content

Rails: class methods or scope  #37

Description

@roman-dubrovsky

Just a question: when should we prefer to use rails scope and where class methods?

These are almost similar things ( one different. That if the lambda (or logic) returns nil, scope returns the current value in this, class method returns nil) See https://www.justinweiss.com/articles/should-you-use-scopes-or-class-methods/

Usually, I use the rule. I prefer to use scope for subqueries, but move it to class methods if it needs to use do end block

# ok
def self.active
  where(finished: false)
end

# better 
scope :active, -> { where(finished: false) }

# bad 
scope :active, -> do 
  where(finished: false) 
    .joins(:statuses)
end

# good 
def self.active
  where(finished: false) 
    .joins(:statuses)
end

Your thoughts?

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions