Colton Seal
Colton Seal

Reputation: 379

How to randomize data output in a View

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

Upvotes: 0

Views: 33

Answers (2)

Rubyrider
Rubyrider

Reputation: 3587

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.

Upvotes: 1

Erwin Brandstetter
Erwin Brandstetter

Reputation: 657922

ORDER BY random()

Or more sophisticated methods:

Upvotes: 0

Related Questions