Skip to content

Instantly share code, notes, and snippets.

@victorcreed
Last active December 22, 2015 19:29
Show Gist options
  • Save victorcreed/6519758 to your computer and use it in GitHub Desktop.
Save victorcreed/6519758 to your computer and use it in GitHub Desktop.
another stupid experiment. I have to count the user individual project tasks' hours. User relation with Project is HBTM and task relation with Project is one project has many tasks. I want to Do User.find(1).projects.first.user_hours_count. so i achive this how
#### app/classes/activity_class.rb
require File.join(Rails.root, "app", "classes", "concerns", "methods")
class ActivityClass
include Classes::Concerns::Methods
def user_projects
user.projects.date_cont(params[:project_date_cont]).search(params[:project_search]).result( distinct: true ).collect do |project|
project.temp_user = user
def project.user_hours_count
temp_user.projects.find(id).tasks.map(&:hours).map(&:to_f).sum
end
project
end
end
end
#### app/classes/concerns/methods.rb
require 'active_support/concern'
module Classes
module Concerns
module Methods
extend ActiveSupport::Concern
included do
attr_accessor :params, :user
def initialize(params={})
@params = params
end
def user
@user ||= User.find(@params[:user_id])
end
def current_projects
user.projects.inprogress
end
def completed_projects
user.projects.completed
end
def user_projects
user.projects.date_cont(params[:project_date_cont]).search(params[:project_search]).result( distinct: true )
end
def user_tasks_for(p)
p.tasks.where(user_id: user.id)
end
end
end
end
end
######################################
######### results ####################
########## 2.0.0p247 :001 > ActivityClass.new({user_id: 1}).user_projects.first.user_hours_count
# User Load (0.5ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
# Project Load (0.1ms) SELECT DISTINCT `projects`.* FROM `projects` INNER JOIN `projects_users` ON `projects`.`id` = #`projects_users`.`project_id` WHERE `projects_users`.`user_id` = 1 AND (projects_users.role IS NULL OR projects_users.role != #'assignor')
# Project Load (0.1ms) SELECT `projects`.* FROM `projects` INNER JOIN `projects_users` ON `projects`.`id` = #`projects_users`.`project_id` WHERE `projects_users`.`user_id` = 1 AND `projects`.`id` = 1 AND (projects_users.role IS NULL OR #projects_users.role != 'assignor') LIMIT 1
# Task Load (0.1ms) SELECT `tasks`.* FROM `tasks` WHERE `tasks`.`project_id` = 1
=> 20.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment