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])
精彩评论