0

使用 Rails 3.2。假设我想要 2 个选项:

  1. 获取所有旅行照片。
  2. 获取第一张旅行照片。

我有以下代码:

# trip.rb
class Trip < ActiveRecord::Base
  has_many :trip_days

  def trip_photos
    if (photos = trip_days.map(&:spots).flatten.map(&:photos).flatten.map)
      photos.each do |photo|
        photo.url(:picture_preview)
      end
    end 
  end

  def trip_photo
    trip_photos.first
  end
end

# trip_day.rb
class TripDay < ActiveRecord::Base
  belongs_to :trip
  has_many :trip_day_spots
  has_many :spots, :through => :trip_day_spots
end

# trip_day_spot.rb
class TripDaySpot < ActiveRecord::Base
  belongs_to :trip_day
  belongs_to :spot
end

#spot.rb
class Spot < ActiveRecord::Base
end

# trips_controller.rb
class TripsController < ApplicationController
  def index    
    @trips = Trip.public.paginate(:page => params[:page], :per_page => 25)
  end
end

正如预期的那样,该trip_photos方法生成了大量的 SQL 查询。我想知道是否有更好的方法来做到这一点?

4

3 回答 3

0

代码工作正常,但要急切加载,只需添加:include

# trips_controller.rb
class TripsController < ApplicationController
  def index    
    @trips = Trip.public.paginate(:include => [:trip_days => [:spots => :photos]], :page => params[:page], :per_page => 25)
  end
end
于 2013-03-27T15:57:37.193 回答
0

这可能不是最常见的方式,但如果你真的想一次击中所有的位置,你可以这样做:

def spots
 Spot.joins("join trip_days_spots on spots.id = trip_days_spots.spot_id join trip_days on trip_days.id = trip_days_spots.trip_day_id join trips on trips.id = trip_days.trip_id").where("trips.id = ?", self.id)
end

然后将循环更改为:

def trip_photos
  spots.map(&:photos).flatten.each do |photo|
    photo.url(:picture_preview)
  end
end
于 2013-03-26T18:11:41.383 回答
0

这是因为 N+1 个查询。在这种情况下,我们需要预先加载基础对象的所有关联,这样当您调用它的关联对象时,它不会触发任何查询来获取它们,而只是从其缓存的对象中获取它们。

希望这会奏效,但未经测试。我假设并编写了以下查询。

def trip_photos
  user_trip_days = trip_days.includes(:spots => :photos)
  photos = user_trip_days.collect {|trip_day| trip_day.spots.map(&:photos).flatten}.flatten
  photos.each do |photo|
    photo.url(:picture_preview)
  end if photos
end

如果您有任何错误,请告诉我。

有关在 ActiveRecord 中急切加载关联对象的更多信息,请参阅

RailsRails castRails Tips指南

于 2013-03-26T17:29:52.357 回答