使用Rails 3.2。假設我想要2個選項:Ruby on Rails中更好的遞歸循環
- 獲取所有旅行照片。
- 獲取第一張旅行照片。
我有以下代碼:
# 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查詢。我想知道有沒有更好的方法來做到這一點?
感謝。當我通過'trip_photos'運行'trip_photo'時,我有'''的東西,但沒有時間去修復它,因爲我要出門。它應該返回'.url(:picture_preview'。 –
Victor
2013-03-26 23:59:13