Suppose I have a posts
table, with a boolean column sponsored
.
Is there any way I can get an ActiveRecord relation where every nth post is a (ideally random) sponsored post? Bonus points if n can vary.
I would prefer to do this in the database rather than Ruby arrays, since I would like to be able to paginate my results the same way I do now.
My current best idea is something like this:
sponsored_ids = Post.where(sponsored: true).select :id
normal_ids = Post.where(sponsored: false).select :id
ordered_ids = inject_sponsored_posts(sponsored_ids, normal_ids)
Post.where(id: ordered_ids) # But this wont preserve order :/
Which isn't particularly ideal.