Results 1 to 2 of 2
Apr 9, 2007, 13:42 #1
Retrieve random photo form each gallery
Hi guys. I'm trying to find the cleanest way to perform this opration.
I have two models: A Gallery and a Photo.
As expected, a Gallery "has many" Photos and a Photo :"belongs to" a Gallery.
Now on my gallery/index page, I want to list all my galleries (by name) and underneath each gallery name, display a random photo from that gallery. This scenario seems to encroach into the territory of both models.
I'm guessing that since the controller should return a collection of Photos, the Photo controller should be the one to use...but it makes since to use the "gallery/index" URL...
Apr 9, 2007, 14:51 #2
- Join Date
- Jul 2004
- Gerodieville Central, UK
- 0 Post(s)
- 0 Thread(s)
Assuming Rails 1.2.x
Your routes will be something like:
map.resources :galleries do |gallery| gallery.resources :photos end
in you controllers....
class GalleriesController < ApplicationController # Show all galleies: /galleries (galleries_path) def index end end class PhotosController < ApplicationController before_filter :find_gallery attr_reader :gallery helper_method :gallery # Show photos for a given gallery def index # All your photos are in gallery.photos end # Show a photo: /galleries/:gallery_id/photos/:id (photos_path(gallery, photo)) def show @photo = gallery.photos.find params[:id] # Other stuff here end private def find_gallery @gallery = Gallery.find params[:gallery_id] end end