2014-06-30 2 views
0

나는 다음과 같은 구조의 테이블에 레일에 액티브를 사용 (SQL 쿼리)에 의해 그룹을 위해 노력하고 있어요 : computed_hours의 합을 반환그룹 쿼리 액티브

id (integer) 
user_id (integer, foreign key from the users table) 
work_date (date, e.g., 2014-06-02) 
computed_hours (integer, e.g., 4) 
computed_minutes (integer, e.g., 30) 

내가 원하는 쿼리 및 , 내가 좋아하는 것, 예를 들어, 그것은

2014년 6월 2일 4.5 (computed_hours 및 computed_minutes을 반환 USER_ID = 2, 말할,

그래서 : computed_minutes는 특정 월의 각 날짜에 대해 특정 사용자에 대한 합계 합계) 2014-06-05 3.25 ......

위의 테이블을 billables라고하고 해당 모델의 이름을 Billable이라고 가정하면 어떻게 ActiveRecord에 기록 할 수 있습니까?

미리 감사드립니다. 당신은 매개 변수로 (날짜의 일부로서) USER_ID 달을 통과 가정

답변

0

이 작동합니다 :

userid  = params[:user_id] 
date_start = Date.parse(params[:date]).at_beginning_of_month - 1.days 
date_end = Date.parse(params[:date]).at_end_of_month  + 1.days 

Billable.all. 
     select('work_date, 
       sum(computed_hours) as total_hours, 
       sum(computed_minutes) as total_minutes'). 
     where('user_id = ? and (work_date > ? and work_date < ?)', 
       userid, date_start, date_end). 
     group(:work_date) 

을 그리고, 그 결과 각 행 @billable을 위해 당신이해야합니다 :

@billable.user_id 
@billable.total_hours 
@billable.total_minutes 
가능성이 이벤트에

사용중인 : UPDATE

Postgres를 사용하면 쉽게 오버라이드 할 수있는 상상도 못할 오류가 발생합니다.

결과 SQL은 "billable"."id"으로 쿼리를 정렬하려고 시도하므로 PostgresGROUP BY "billable"."id"을 사용해야합니다.

NO ORDERING을 요청하거나 선택한 필드 (이 경우 work_date이어야 함)로 주문하면이 동작을 건너 뛸 수 있습니다.

  group(:work_date).order(false) 

또는

  group(:work_date).order(:work_date) 
:

따라서, 솔루션에 마지막 줄을 변경 필요