CenCalRuby / freshfoodconnect

0 stars 0 forks source link

Consider scopes for simple model queries #3

Open josephbridgwaterrowe opened 8 years ago

josephbridgwaterrowe commented 8 years ago

The User model uses class methods to perform simple query "extensions" which could be achieved using scopes.

Whilst I try and avoid scopes because I believe they can lead to query leakage I do believe that these kinds of things are a good case for a scope.

Source

# /app/models/user.rb
class User
  # ...

  def self.active
    where(deleted_at: nil)
  end

  def self.admins
    where(admin: true)
  end

  def self.cyclists
    where.not(assigned_zone_id: nil)
  end

  def self.donors
    joins(:location)
  end

  # ...
end

With scopes:

# /app/models/user.rb
class User
  # ...

  scope :active, -> { where(deleted_at: nil) }
  scope :admin, -> { where(admin: true) }
  scope :cyclists, -> { where.not(assigned_zone_id: nil) }
  scope :donors, -> { joins(:location) }

  # ...
end
frank-west-iii commented 8 years ago

@josephbridgwaterrowe, your view on scopes is intriguing. Can you expand the ideas behind query leakage? I don't think I have ever heard this before now.

frank-west-iii commented 8 years ago

Also this article has a pretty good rundown of some thoughts on this subject.

http://www.justinweiss.com/articles/should-you-use-scopes-or-class-methods/

josephbridgwaterrowe commented 8 years ago

@frank-west-iii unfortunately I need to do some work however I agree with this from the article:

The thing I love most about scopes is that they express intent. You’re telling the next person who reads your code, “This method can be chained, will eventually turn into a list of objects, and will help you select the right set of objects.” That’s a whole lot more than a generic class method says.

And I will elaborate on query leakage later.

josephbridgwaterrowe commented 1 year ago

Hi @frank-west-iii

I can't actually remember what I meant about query leakage 🙂 . I can only imagine that I was thinking (and being concerned over) large queries being embedded in scopes where they should probably live in a query object.