2011-05-15 60 views
0

鉴于以下型号:查询到基于嵌套资源收益模型X Y

Thread (id, title, timestamps) 
ThreadParticipant (id, thread_id, user_id, read(boolean), timestamps) 
Comment (id, thread_id, user_id) 

如何查询来构建它返回:所有线程获取最新的主题评论(Thread.comment.first )等于current_user?

...返回线程最后一个comment.user_id == current_user.id?

想法?

+0

让我知道,如果问题是令人困惑 – AnApprentice 2011-05-15 20:52:06

回答

1

尝试像[未经测试的代码]:

Thread.find_by_sql(["Select * from Threads where ((select user_id from comments where threads.id = comments.thread_id ORDER by created_at DESC LIMIT 1) = ?)", current_user.id ]) 

或本试用一下(不知道是否要求不同会自动挑选第一个,但我猜它应该):

Thread.find(:all, :joins => :comments , :select => ["distinct threads.id"], :conditions => ["comments.user_id = ?", current_user.id]) 
+0

谢谢,但你认为有办法不求助于直写SQL?试图避免这是轨道友好 – AnApprentice 2011-05-16 01:02:56

+1

增加了另一条线。顺便说一句,使用SQL没有任何问题,你也可以将它放在模型中,并用一个方法包装它,这样它在控制器中仍然看起来很优雅。有时你可能能够编写更高效的SQL,Rails会自动为你做。 – Tam 2011-05-16 05:55:31