现在已经有个这样的关联关系
# 用户
class User < ApplicationRecord
has_many :group_users
has_many :groups, through: :group_users
has_many :messages
end
# 小组
class Group < ApplicationRecord
has_many :group_users
has_many :users ,through: :group_users
has_many :messages
end
# 小组消息
class Message < ApplicationRecord
belongs_to :group
belongs_to :user
end
# 小组和成员的关联表
class GroupUser < ApplicationRecord
belongs_to :group
belongs_to :user
end
我在 ERB 模板里面写了这样一句,目的是获取当前这条消息所在小组的所有用户的名称,并且使用','连接他们
<% @messages.each do |message| %>
<strong>Group Chat: <%= message.group.users.map(&:name).join(',')%></strong><br/>
<% end %>
这样子会产生大量的 N+1 query 查询
SELECT "groups".* FROM "groups" WHERE "groups"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
SELECT "users".* FROM "users" INNER JOIN "group_users" ON "users"."id" = "group_users"."user_id" WHERE "group_users"."group_id" = $1 [["group_id", 1]]
SELECT "groups".* FROM "groups" WHERE "groups"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
SELECT "users".* FROM "users" INNER JOIN "group_users" ON "users"."id" = "group_users"."user_id" WHERE "group_users"."group_id" = $1 [["group_id", 2]]
那么,请问如何避免这种 N+1 query 查询,或者最好的做法是怎样,请指教?