2013-03-26 2 views
0

Rails 3.2 사용. 2 가지 옵션을 원한다고 가정 해 봅시다 :Ruby on Rails의 재귀 루프 개선

  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 쿼리를 많이 생성 :

나는 다음과 같은 코드가 있습니다. 더 좋은 방법이 있는지 궁금합니다.

답변

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 
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 

오류가 발생하면 알려주세요. 당신이 진정으로 모두를 얻기 위해 원하는 경우 액티브의 열망로드 관련 개체에 대한 추가 정보를 원하시면

, 가장 레일-Y 방법을하지 않을 수 있습니다

Guides for RailsRails castRails Tips

+0

감사합니다. 'trip_photo '를 통해'trip_photo'를 실행할 때'# '과 같은 것을 얻었지만, 나가기 때문에 고칠 시간이 없습니다. 그것은'.url (: picture_preview'. – Victor

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 

: 1 안타의 명소 당신이 뭔가를 할 수