2016-08-17 106 views
1

我有一个rails应用程序,我有以下模型。rails包含查询加载包含模型的全部数据

BookingHotel 
    has_many :hotel_picture_partners, through: :hotel_pictures 
    has_many :booking_hotel_partner_details, dependent: :destroy 

BookingHotelPartnerDetail 
    belongs_to :booking_hotel 

HotelPicturePartner 
    belongs_to :hotel_picture, dependent: :destroy 

我有一个查询如下

@booking_hotel_partner_details = BookingHotelPartnerDetail.unscoped.select(:id, :booking_hotel_id, :partner_booking_hotel_id).includes(booking_hotel: :hotel_picture_partners) 

,因为它为加载模型包含的所有数据这使得在压力下的记忆。

有没有办法只能从booking_hotels加载选择字段& hotel_picture_partners表?

另外我想获得一个activerecord数组作为响应。

+0

的可能的复制[Rails 3中 - 选择具有包括哪些?(http://stackoverflow.com/questions/4047833/rails-3-select-with-include ) –

回答

1

pluck方法仅加载属性,不加载整个模型。检查它:http://apidock.com/rails/ActiveRecord/Calculations/pluck

尝试重写它像这样: BookingHotelPartnerDetail.unscoped.select('booking_hotels.id as bh_id', 'hotel_picture_partners.id as hpp_id').joins(booking_hotel: :hotel_picture_partners)

+0

我想加载包含的模型,但采摘会给我一个数组 – RamanSM

+0

检查更新的答案 – AndreyS

+0

这似乎是正确的安德烈。这不会加载内存中的所有关联记录吗? – RamanSM