1

I have a model Project that appears in multiple controllers in an application I'm building as it appears on multiple pages. The where clause for this isn't complicated, per se, but I feel like it is too large to be repeated on every method requiring projects with these constraints.

My question is, where, if possible, does this common call for Projects go? In .NET, I'd have a ProjectService class with a method that would return all projects, and another that returned all projects that satisfied my conditions. I'm new to Rails so I'm struggling to see where this fits in?

Marcelo De Polli
  • 28,123
  • 4
  • 37
  • 47
ediblecode
  • 11,701
  • 19
  • 68
  • 116

1 Answers1

4

You can either use a class method or Scopes.

class Project < ActiveRecord::Base
  # example for a scope
  scope :awkward_projects,where(awkward: true)

  # example for a class method.     
  def self.awkward_projects
    where(awkward: true)
  end

end

Its very safe to do what was once given in a SO answer. Read below and choose carefully.

Quoting an answer

"Generally, I use scope entries for simple one-liners to filter down my result set. However, if I'm doing anything complicated in a "scope" which may require detailed logic, lambdas, multiple lines, etc., I prefer to use a class method. And as you caught, if I need to return counts or anything like that, I use a class method."

Community
  • 1
  • 1
beck03076
  • 3,268
  • 2
  • 27
  • 37