1
我有兩個相關的模型:聊天和用戶通過成員模型導軌的has_many:通過和N + 1
class Chat < ActiveRecord::Base
has_many :memberships
has_many :members, through: :memberships
end
class Membership < ActiveRecord::Base
belongs_to :chat
belongs_to :member, class_name: "User", foreign_key: 'user_id'
end
在控制器我檢索記錄這樣的:
@chats = Chat.joins(:memberships).includes([:owner, :memberships=>:member])
.where("chats.owner_id = ? OR memberships.user_id = ?", current_user.id, current_user.id)
,並鑑於我與JBuilder一樣顯示聊天記錄:
json.extract! @chat, :id
json.members @chat.memberships.order('id ASC') do |membership|
json.name membership.member.name
end
end
但Rails生成大量的db查詢和視圖rende環需要很長時間:
Completed 200 OK in 1597ms (Views: 1393.8ms | ActiveRecord: 150.8ms)
如何優化和加快這些查詢?
http://stackoverflow.com/a/26251892/525478 –