我有一家酒店的ruby on rails应用程序,该应用程序有一个房间页面。酒店房间可以为他们打开各种不同的门票,在我的房间视图中,显示房间号,我正在助手中使用此查询来获取单个房间的门票计数
helper/room.rb
SELECT COUNT(*) FROM "tickets" WHERE "tickets"."room_id" = ? AND (status = ? OR status = ? )
room.slim
- @rooms.each do |floor_number, rooms|
- if rooms.present?
h1.separator
- if (@current_view.eql? "room_type") || (params[:action].eql? "room_type")
span= floor_number
- else
span= "Floor-#{floor_number}"
.cards-container
- rooms.each do |room|
= link_to get_show_page_url(room) do
.col-md-3.room-card_room.new-floor-other{ style="background-color:#{card_background_color(room, @maintenance_type, @inspection_type)}" }
.new-floor-inner
- if room.occupy_or_dnd? && (!@current_view.eql? "maintenance") && (!@current_view.eql? "inspection")
span
- if room.dnd?
= image_tag('dnd', class: "guest-occupy-img")
- else
= image_tag('man_to_white', class: "guest-occupy-img")
h4= room.location
- if (@current_view.eql? "maintenance") || (@current_view.eql? "inspection")
h6.room_status
| (
= last_maintained(room, @maintenance_type, @inspection_type)
| )
span.room_hilton_honors= room.hilton_honors
- count = room.open_tickets_count || 0
- if count > 0 && (!@current_view.eql? "maintenance") && (!@current_view.eql? "inspection")
span.circle = count
room_controller
before_action :get_room, only: [:show, :update]
def get_room
@room = Room.find_by_id(params[:id])
@featured_tickets = ImportTicket.where(request_type: "PREVENTIVE MAINTENANCE", featured:true)
end
room.open_tickets_count
是会多次触发的查询,并且open_tickets
是在助手内部定义的,并且计数显示该房间的门票数量
这可以正常工作,但是就性能而言,它会创建更多的处理时间,因为在单个请求中多次触发该单个查询。好像有100个房间一样,该查询将触发100次以检查每个房间的门票总数
有没有一种方法可以使我在良好的性能时间内达到目标?
答案 0 :(得分:0)
我假设您有一个包含所有房间ID的变量。然后,您可以将where
与该数组一起使用,并将count
与group
一起使用:
Ticket.where(room_id: room_ids).group(:room_id).count
返回将如下所示:
{ 1 => 5, 2 => 3 }
这意味着1号房间有5张票,而2号房间则有3张票。