1
\$\begingroup\$

I moved a lot of the loading/logic from my view to my controller, and it's working great but after I did this I now have several very similar helper methods in my controller.

What is a more efficient way of doing this? Is there? I assume get_last_task_owed and get_first_task_owed I would be able to do in the view by finding the .first and .last of the record respectively.

  def get_projects_owed
    current_user.projects.where('end_date > ?', Date.today).order(:start_date).pluck(:name, :start_date, :end_date)

  end

  def get_all_projects
    current_user.projects.order(:start_date).pluck(:name, :start_date, :end_date)
  end

  def get_all_tasks
    @project.tasks.order(:product, :task_start_date).pluck(:product, :task_name, :task_start_date, :task_end_date).to_json
  end

  def get_last_task_owed
    tasks = @project.tasks
    tasks.where('task_end_date >= ?', Date.today).order('task_end_date DESC').first.task_end_date.strftime("%B %d, %Y")
  end

  def get_first_task_owed
    tasks = @project.tasks
    tasks.where('task_end_date >= ?', Date.today).order('task_end_date ASC').first.task_end_date.strftime("%B %d, %Y")
  end

  helper_method :get_projects_owed
  helper_method :get_all_projects
  helper_method :get_clients_with_projects
  helper_method :get_all_tasks
  helper_method :get_last_task_owed
  helper_method :get_first_task_owed
\$\endgroup\$
0
\$\begingroup\$

One possible improvement is using scopes:

def get_projects_owed
  current_user.projects.owed.recent_first.pluck(:name, :start_date, :end_date)
end

def get_all_projects
  current_user.projects.recent_first.pluck(:name, :start_date, :end_date)
end

def get_last_task_owed
  get_owed_tasks.last.task_end_date.strftime("%B %d, %Y")
end

def get_first_task_owed
  get_owed_tasks.first.task_end_date.strftime("%B %d, %Y")
end

def get_owed_tasks
  tasks = @project.tasks
  tasks.owed.order('task_end_date DESC')
end

helper_method :get_owed_tasks


class Project
  scope :owed, -> { where('end_date > ?', Date.today) }
  scope :recent_first, -> { order(:start_date) }
end


class Task
  scope :owed, -> { where('task_end_date >= ?', Date.today) }
end
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.