我与所有成员一起搜索特殊群组:
控制器:
class Groups::MembersController < ApplicationController
def index
@group = Group.find_by_name(params[:groupname])
@search = @group.members.ransack(params[:q])
@members = @search.result().includes(:user).page(params[:page]).per(5)
respond_to do |format|
format.js
format.html
end
end
...
型号:
class Member < ApplicationRecord
belongs_to :user
belongs_to :group
end
查看: 这些投注已经存入。
...
- puts 'Out'
- @members.each do |member|
- puts 'In'
- user = member.user
- userShow = user_path(user)
.list-group-item{id: member.id}
...
输出:
Started GET "/groups/Test/members" for 127.0.0.1 at
Processing by Groups::MembersController#index as HTML
Parameters: {"groupname"=>"Test"}
Group Load (0.0ms) SELECT "groups".* FROM "groups" WHERE "groups"."name" = ? LIMIT ? [["name", "Test"], ["LIMIT", 1]]
Rendering groups/members/index.html.haml within layouts/application
Rendered layouts/nav/sidebar/_groups.html.haml (4.0ms)
Out
Member Load (0.0ms) SELECT "members".* FROM "members" WHERE "members"."group_id" = ? LIMIT ? OFFSET ? [["group_id", 2], ["LIMIT", 5], ["OFFSET", 0]]
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" IN (15, 24, 48, 9, 4)
In
Member Load (0.0ms) SELECT "members".* FROM "members" WHERE "members"."group_id" = ? LIMIT ? [["group_id", 2], ["LIMIT", 11]]
In
CACHE Member Load (0.0ms) SELECT "members".* FROM "members" WHERE "members"."group_id" = ? LIMIT ? [["group_id", 2], ["LIMIT", 11]]
In
CACHE Member Load (0.0ms) SELECT "members".* FROM "members" WHERE "members"."group_id" = ? LIMIT ? [["group_id", 2], ["LIMIT", 11]]
In
CACHE Member Load (0.0ms) SELECT "members".* FROM "members" WHERE "members"."group_id" = ? LIMIT ? [["group_id", 2], ["LIMIT", 11]]
In
CACHE Member Load (0.0ms) SELECT "members".* FROM "members" WHERE "members"."group_id" = ? LIMIT ? [["group_id", 2], ["LIMIT", 11]]
Rendered groups/members/_index_list.html.haml (7068.8ms)
(0.0ms) SELECT COUNT(*) FROM "members" WHERE "members"."group_id" = ? [["group_id", 2]]
Rendered groups/members/index.html.haml within layouts/application (7313.5ms)
Rendered layouts/_head.html.haml (274.7ms)
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]]
Rendered layouts/header/_default.html.haml (7.0ms)
Rendered layouts/_nav.html.haml (2.0ms)
Rendered layouts/_flash.html.haml (14.0ms)
Completed 200 OK in 7965ms (Views: 7931.9ms | ActiveRecord: 1.0ms)
我不明白为什么在每个循环中执行查询的原因。 即使用CACHE完成,也要花费我的性能。 我能解决吗?
答案 0 :(得分:1)
我认为你错误地认为延迟在哪里。使用一些时间戳记录您的代码并发布会发生的事情:
- puts "before loop: #{Time.now.to_s(:utc)}"
- puts 'Out'
- @members.each do |member|
- puts "In loop #{Time.now.to_s(:utc)}"
- user = member.user
- puts "after member.user call #{Time.now.to_s(:utc)}"
- userShow = user_path(user)
.list-group-item{id: member.id}
- puts "End loop #{Time.now.to_s(:utc)}"