2016-12-25 163 views
0

的DB关系的轨道模型优化查询使用活动记录或SQL查询。我基本上想要减少数据库查询和上面的代码完成循环的时间。使用活动记录轨道

在此先感谢。

+0

听起来像一个工作,左和加入一组和一组。你有没有尝试做一个基本的教程到SQL? – Shadow

+0

你应该在'users'表中存储'unread_count'列来为每个用户存储'unread_count'。 – Thanh

+0

Thanh我可以将unread_count存储在用户表中,因为我使用此Model.import方法在user_messages表中插入批量数据。 – user1969191

回答

1

你可以做这样的事情:

users = User.where(id: ids).includes(:user_messages) 
users.each do |user| 
    unread_count = user.user_messages.where(:folder => user.inbox_id, :read => false).count 
    puts "UserID #{user.id} ---- Unread Message count #{unread_count}" 
end 

既然你渴望装载user_messages,也不会触发回路内的任何其他数据库查询。只有1个查询来获取用户和它的user_messages。

或者,你可以这样做:

user_messages = UserMessage.joins(:user).where('folder = users.inbox_id AND read = false').group(:user_id).count 
# user_messages = {1=>10, 2=>19} 
# Here keys are user ids and values are no of user_messages for that user 

user_messages.each do |user_id,unread_msg_count| 
    puts "UserID #{user_id} ---- Unread Message count #{unread_msg_count}" 
end 

PS:我没有测试过任何代码,请,如果您有任何意见的任何错误。我在这里假设你想放一个用户ID并根据它修改我的代码puts "UserID #{ids},因为在你的代码中它会打印所有的ids ids