0

How would one randomize data in a view? The below code currently displays meals in the order they were entered into the DB.

e.g.

    <% @meals.each do |r| %>
        <div class = "col-md-4">
          <div class = "rest-box">
              <center><%= image_tag r.meal_photo.url(:medium) %></center>
          </div>
        </div>
    <% end %>
Colton Seal
  • 379
  • 2
  • 14

2 Answers2

1

In view level you can use:

 <% @meals.shuffle.each do |r| %>
    <div class = "col-md-4">
      <div class = "rest-box">
          <center><%= image_tag r.meal_photo.url(:medium) %></center>
      </div>
    </div>
<% end %>

But it is preferred that you do it on your model in the controller.

@meals = Meal.order('RANDOM()')  # example

By the way, if you need it always you can make it your default scope like this in your model file:

default_scope -> {order(' RANDOM()' )}

So this will always return data randomly whenever you query for many results.

Rubyrider
  • 3,567
  • 1
  • 28
  • 34
0
ORDER BY random()

Or more sophisticated methods:

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228