SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot tconley79's Avatar
    Join Date
    Feb 2004
    Location
    Miami
    Posts
    176
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

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

    Any thoughts?

    Thanks.

  2. #2
    Resident Java Hater
    Join Date
    Jul 2004
    Location
    Gerodieville Central, UK
    Posts
    446
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Assuming Rails 1.2.x

    Your routes will be something like:

    Code:
    map.resources :galleries do |gallery|
      gallery.resources :photos
    end
    Now you will have URLs / Path's like ... galleries_path, photos_path(gallery), photo_path(glallery, photo)

    in you controllers....

    Code:
    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
    You won't need a show method in the galleries controller, as the photos controller index will be pretty much the same thing.
    http://virtualfunction.net - Rails Web Development
    http://squaremove.co.uk - Rails powered Property Listings


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •