Rails random ActiveRecord while paginating

2019-08-19 04:02发布

问题:

I am trying to display a series of photos in random order while paginating them. Trouble is, on each page of the pagination the random array is regenerated; so a user can see photos on page 2 that he's already seen on page 1. Lame. Here's my controller:

def index
  @photos = Photo.order('random()').paginate(:per_page => 12, :page => params[:page])
end

I've been thinking it for a while and can't think of any reasonable solution. Is this easily doable? It seems like a pretty common function, but I may just have to ditch the random thing. Thoughts?

回答1:

You can introduce some orderness to randomness by specifying a seed. Using this, the subsequent calls would give you repeatable ordering.

Each database offers a different way to specify the seed value. For e.g., in MySQL,

@photos = Photo.order('rand(0.5)').paginate(:per_page => 12, :page => params[:page])

Here 0.5 would be the seed to rand() function.

Similarly, Postgres has a setseed() function. I am not sure what database you are using. Anyway, I hope you get the idea.