rails - 一点儿对于 includes, join的理解

访问量: 425

下面这段代码:

             <td><%= consumption_entertainment.entertainment.name %>
             <td><%= consumption_entertainment.cost %>
             <td><%= consumption_entertainment.check_in_order.room.name rescue '无' %>
             <td><%= consumption_entertainment.check_in_order.guest.name rescue '无' %>

对应的查询:

   def index 
     @consumption_entertainments = ConsumptionEntertainment
       .includes([:entertainment, {:check_in_order => [:room, :guest]}])
       .joins(:entertainment)
       .where("entertainments.company_id = ?", current_user.company_id)
       .order('comsumption_entertainments.created_at desc').page(params[:page])
   end

会生成: (可以注意到: includes 会生成 inner join 和 left outer join 语句)

SELECT  `consumption_entertainments`.`id` AS t0_r0, `consumption_entertainments`.`date` .............
    FROM `consumption_entertainments` 
    INNER JOIN `entertainments` ON `entertainments`.`id` = `consumption_entertainments`.`entertainment_id` 
    LEFT OUTER JOIN `check_in_orders` ON `check_in_orders`.`id` = `consumption_entertainments`.`check_in_order_id` 
    LEFT OUTER JOIN `rooms` ON `rooms`.`id` = `check_in_orders`.`room_id` 
    LEFT OUTER JOIN `guests` ON `guests`.`id` = `check_in_orders`.`guest_id` 
    WHERE (entertainments.company_id = 1)  
    ORDER BY created_at desc 
    LIMIT 100 OFFSET 0

订阅/RSS Feed

Subscribe

分类/category