简体   繁体   中英

How to select 6 random records from table

My portfolio_controller.rb has an index method like this:

def index
  @portfolio = PortfolioItem.all
end

How can I specify in the condition that the code in this block should be executed 6 times? In other words, how can I access exactly 6 values from the @portfolio object in my view, using a loop? This is what I have so far:

<% @portfolio.shuffle.each do |portfo| %>

Using all , followed by shuffle , is a bad solution for two reasons.

A slight improvement would be to use sample(6) instead of shuffle.first(6) , as this removes a step from the process.

However, the bigger issue here is that Portfolio.all.<something> (where the <something> method requires converting the data into a ruby Array ) will fetch all of the data into memory - which is a bad idea. As the table grows, this will become a bigger performance issue.

A better idea is to perform the "random selection" in SQL (with the order and limit methods), rather than in ruby. This avoids the need to fetch other data into memory.

The exact solution is database-specific, unfortunately. For PostgreSQL and SQLite, use:

Portfolio.order('RANDOM()').limit(6).each do |portfolio|

Or for MySQL, use:

Portfolio.order('RAND()').limit(6).each do |portfolio|

You could define this as a helper in the Portfolio model - for example:

class Portfolio < ApplicationRecord
  # ...

  scope :random_sample, ->(n) { order('RANDOM()').limit(n) }

  # ...
end

And then in your view:

@portfolio.random_sample(6).each do |portfolio|

You can something like this :

 <%(1..6).each do |i| %>
     <% #your statements %>
 <%end%>
<% @portfolio.shuffle.each_with_index do |portfo, index| %>
  <%if index <= 6%>
    <p><%= portfo.title %></p>
  <%end%>
<% end %>

Or You can do it as

<% @portfolio.shuffle.take(6).each do |portfo| %>
    <p><%= portfo.title %></p>
<% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM