Reputation: 379
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
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