2016-06-07 28 views
1

選擇具有3列重複的記錄在以下情形:ActiveRecord的帳戶

ClassHour (teacher_id, room_id, hour_id, group_id, subject_id)

我需要獲得一個給定的老師的所有class_hours而不必考慮的GROUP_ID。

id teacher_id room_id hour_id group_id subject_id 
1   1   1   1   1   1 
2   1   1   1   2   1 
3   1   2   2   1   1 
4   2   1   3   2   3 

我只需要獲得給定教師的unique records on room_id, hour_id and subject_id

這是:teacher_one.schedule應返回class_hours with ids [1,3],因爲與id == 2一個不是唯一的。

簡而言之:如果我的老師有ID 1teacher.schedule需要返回:

id teacher_id room_id hour_id group_id subject_id 
1   1   1   1   1   1 
3   1   2   2   1   1 
+0

添加了所需的結果@Strawberry –

回答

0

一個HackHands會議結束後,我們與此結束,即充分作品:

class Teacher 
    ... 
    def schedule 
    ids = ClassHour.find_by_sql(['SELECT max(class_hours.id) mid FROM class_hours inner join hours on class_hours.hour_id = hours.id inner join rooms on class_hours.room_id = rooms.id where class_hours.teacher_id = ? group by hours.id, rooms.id', self.id]).map { |x| x['mid'] } 
    ClassHour.find ids 
    end 
end 

但我不完全明白爲什麼這個查詢按我的意思工作。如果有人能解釋,那會很好。