Find a random entry from an association in rails

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 the Gallery, in which there are many photos. I want to display an image (preferably random rather than: first) from each gallery on the gallery index page. I know that the code that I have is incorrect, because I did not describe which image to select from the gallery, but I'm not sure how to do it ... I thought that using @photos = @galleries.photos.find(:first)would work, but I get the undefined method 'photos 'in the controller.

+3
source share
3 answers

This works in Rails 2 + MySQL

class Photos < ActiveRecord::Base
  # for MySQL:
  named_scope :random, lambda { |n| {:order => "RAND()", :limit => n || 1 }}
  # for SQLite and PostgreSQL
  named_scope :random, lambda { |n| {:order => "RANDOM()", :limit => n || 1 }}
end

Then you can do something like

gallery.photos.random[0]

gallery.photos.random 1 , , [0], . gallery.photos.random.first.

, gallery.photos.random(10), 10 .

+3

@galleries - , @galleries.photos.find(:first), @galleries[0].photos.find(:first)

<% for gallery in @galleries %>

<%= image_tag(gallery.photos.order('rand()')) %>
0

@galleries , . .

, for :

<% for gallery in @galleries %>
<%= image_tag(gallery.photos.first.image.url(:medium)) %>

, Salils Gallery : -

def random_image()
  photos.all[rand(photos.all.size)]
end

foreach <%= image_tag(gallery.random_image) %>

0
source

Source: https://habr.com/ru/post/1754235/


All Articles