In Rails - How to have one query that has multiple queries? -
in have 3 models here:
- projects
- threads (project_id)
- thread_participations (thread_id, read boolean)
right have list of user's projects, , list shows how many threads unread per project. huge problem here if user has several projects (which users do) causes db hit several queries, 1 per project.
i use rails build query, 1 db hit, returns unread count each of user's project.
here's use today in view:
<% @projects.each_with_index |project, i| %> <%=project %>: <%= thread.unread(current_user,project).count %> <% end %>
and in thread model:
scope :unread, lambda { |user,project| includes(:project,:thread_participations).where(:project_id => project.id, :thread_participations => {:read => false, :user_id => user.id}) }
any suggestions on how this? model should live in? maybe user's model since not project or thread specific?
thanks
there couple of ways structure query, here one.
you can perform in single query , loop on results. first create scope on thread participations unread user. use scope , include threads , projects, group project id (so getting unread threads project) , count number of unread threads counting threads.id:
class threadparticipations scope :unread, lambda{ |user| where(user_id: user.id, read: false) } end threadparticipations .unread(current_user) .includes(:thread => :project) .group('projects.id') .count('threads.id') => { 10 => 15, 11 => 10 } # project(10) has 15 unread threads , project(11) has 10 unread threads
Comments
Post a Comment