rails重构AR查询

时间:2016-05-13 19:13:26

标签: ruby-on-rails activerecord refactoring

我正在尝试重构我的范围和我的控制器,但我觉得它可能会更好。从控制器的角度来看,新代码肯定更好,但我认为alltasks范围和all_uncompleted_tasks_ordered_by_deadline实例方法有点奇怪。有什么想法吗?

用户:

has_many :assigned_tasks, class_name: "Task", foreign_key: "assigner_id", dependent: :destroy
has_many :executed_tasks, class_name: "Task", foreign_key: "executor_id", dependent: :destroy

任务:

belongs_to :assigner, class_name: "User"
belongs_to :executor, class_name: "User"
scope :alltasks, -> (u) { where('executor_id = ? OR assigner_id = ?', u.id, u.id) }
scope :uncompleted, -> { where(completed_at: nil) }

任务控制器

def index
  @tasks = Task.alltasks(current_user).uncompleted.includes(:executor, :executor_profile, :assigner, :assigner_profile).order("deadline DESC")
end

新代码:

user.rb

def all_uncompleted_tasks_ordered_by_deadline
  Task.alltasks(self).uncompleted.includes(:executor, :executor_profile, :assigner, :assigner_profile).order("deadline DESC")
end

任务控制器

def index
  @tasks = current_user.all_uncompleted_tasks_ordered_by_deadline
end

1 个答案:

答案 0 :(得分:1)

我宁愿认为all_tasks想要在用户模型中就像分配和执行的那样。也许你可以将它作为方法移动到那里,并在控制器中应用所需的Task范围。

说:

#user.rb
def all_tasks
  Task.where('executor_id = ? OR assigner_id = ?', id, id)
end

#tasks_controller.rb
def index
  @tasks = current_user.all_tasks
                       .uncompleted.includes(:executor, :executor_profile, :assigner, :assigner_profile)
                       .order(deadline: :desc)

end