假设我有一个记录用户和导师之间关系的关系表。我想为每个用户检索最新(即最新)导师。
Relationship.selects("MAX(id) AS newest_relationship_id").group('user_id')
这成功地返回了每个用户的最新关系,作为列newest_relationship_id,但我如何确保therapist_id列将为最新关系返回正确的相应治疗师?
答案 0 :(得分:0)
您可以为特定导师收集新的关系ID,并使用子查询中的那些:
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)