开发者

Query to return Model X based on the nested resources Y

Given the following models:

Thread (id, title, timestamps)
ThreadParticipant (id, thread_id, user_id, read(boolean), timestamps)
C开发者_如何学编程omment (id, thread_id, user_id)

How can a query be constructed where it returns: All Threads where the most recent Thread Comment (Thread.comment.first) is equal to the current_user?

... Return Threads where the last comment.user_id == current_user.id?

Ideas?


Try Something like [Untested code]:

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 ])

OR give this a try (not sure if asking for distinct will automatically pick first one but I'm guessing it should):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜