2013-03-21 63 views
0

假設我有一個關係表記錄用戶和導師之間的關係。我想爲每個用戶檢索最新的(即最新)導師。ActiveRecord分組和相關字段

Relationship.selects("MAX(id) AS newest_relationship_id").group('user_id') 

這成功返回,作爲列newest_relationship_id,每個用戶的最新關係,但如何確保therapist_id列將返回正確的對應治療師爲最新的關係?

+0

待辦事項你在'關係'中有一個'導師'表和'mentor_id'列,或者他們的名字是不同的? – PinnyM 2013-03-21 15:07:43

+0

@PinnyM是的。關係列僅僅是id,mentor_id,user_id – 2013-03-21 15:10:50

+0

另外,你可以對你正在尋找的結果的結構更具體一些嗎?你想要一個散列爲'user => newest_mentor'或其他東西? – PinnyM 2013-03-21 15:17:56

回答

0

您可以收集新關係的IDS特定導師和使用那些在你的子查詢:

mentor = Mentor.find(mentor_id) 
newest_relationship_ids = Relationship.select("MAX(id)").group(:user_id) 
mentor.relationships. 
     includes(:user).      # eager load the user 
     where(:id => newest_relationship_ids). 
     map(&:user)       # collect the user 

你也可以做這一點更有效地使用子查詢:

mentor = Mentor.find(mentor_id) 
newest_relationship_ids = Relationship.select("MAX(id)").group(:user_id).to_sql 
mentor.relationships. 
     includes(:user).   
     where("relationships.id IN (#{newest_relationship_ids}). 
     map(&:user)    
+0

在第一個答案中,如果添加where子句,不會將結果集僅限於導師嗎?這意味着sql甚至不會包含其他指導者關係。所以如果最新的關係是另一個導師,它將不會被包含在結果集中,並且將不正確地返回mentor_id作爲最新的導師。 – 2013-03-21 15:40:44

+0

我喜歡第二個答案,正在考慮這樣做,儘管我會使用.pluck(:id)而不是.to_sql – 2013-03-21 15:41:16

+1

@DavidLesches:在第二個答案中,整個觀點是避免進行2個查詢。 'to_sql'可以幫助你做到這一點。 – PinnyM 2013-03-21 15:44:03