I've got a facade class, which performs SQL queries on other models. I wanted to use scopes, but I am having doubts about where to implement them, and if they are better than using just plain methods. I'm also concern about good programming practice.
First, this are my models
class User < ActiveRecord::Base
has_many :projects
class Project < ActiveRecord::Base
belongs_to :User
has_many :tasks, :inverse_of => :project
class Task < ActiveRecord::Base
belongs_to :project, :inverse_of => :tasks
has_many :instances
class Instance < ActiveRecord::Base
belongs_to :task
Facade class:
def Function1(param)
@var = @user.instances.where("...", param).order(:start_time).group_by { |x| x.method}
end
def Function2
@var = @user.instances.where("...").first
end
def Function3
@var = @user.projects.distinct
end
1) Should function 1 and 2 be on the User model, or in the instances'?
2) Should function3 be on the User model or in the projects'?
3) Could I for example write a 'distinct' scope on projects, and a 'User distinct projects' scope which calls projects'?
1) Should function 1 and 2 be on the User model, or in the instances'?
In the instances - you are restricting the scope of the instances that are returned
2) Should function3 be on the User model or in the projects'?
The project - likewise to above. The user is still the user, but you will be restricting which projects are returned, therefore it's a project scope
3) Could I for example write a 'distinct' scope on projects, and a 'User distinct projects' scope which calls projects'?
Yes, you can do both if you really want to - in practice, it's probably not worth doing the user distinct_projects
scope unless you are likely to reuse the user distinct_projects
scope again somewhere else (eg in another scope). It doesn't save you any typing ;)