Controller:
class GalleriesController < ApplicationController
def index
@galleries = Gallery.all
end
end
View:
<% for gallery in @galleries %>
<%= image_tag(gallery.image.url(:medium)) %>
<% end %>
I have 2 models, Photo which belongs to Gallery,which has many Photos.
I want to display an image (preferably random rather than :first) from each gallery on the gallery index page.
I know the code I have is wrong as I haven’t described which image to select from the gallery, but I’m not sure how to do this… I thought that using @photos = @galleries.photos.find(:first) would work but I get an undefined method ‘photos’ in the controller.
This works in Rails 2 + MySQL
Then you can do something like
gallery.photos.randomwill return 1 Photo randomly, but it will still return an array, that’s why you need the[0]to get the first element of this array. you can also dogallery.photos.random.first.If you want more than one random image you can call
gallery.photos.random(10)to get 10 random photos.