1

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.

AndrewH
  • 3,418
  • 2
  • 15
  • 27
  • What is the use case for this? Why should a random post be tagged as sponsored? – Srdjan Pejic Jan 29 '16 at 18:47
  • I just mean randomly selected from the pre existing sponsored posts. The use case is that advertisers sponsor a post and expect it do be shown to users. – AndrewH Jan 29 '16 at 19:24
  • The accepted answer from this post MIGHT help...http://stackoverflow.com/questions/1680627/activerecord-findarray-of-ids-preserving-order . It's specifically for MySQL, but maybe you could find a similar postgres feature. – Michael Cruz Jan 29 '16 at 21:19

1 Answers1

0

If you're looping through your posts, you could use .each_slice:

<% @posts.each_slice(x) do |post_group| %>
   <% post_group.each do |post| %>

   <% end %>

   <% ... spondored ... %>
<% end %>

--

I can delete this if it's too low ball. Injecting an id into the SQL query is the most efficient way (as per the comments).

Richard Peck
  • 76,116
  • 9
  • 93
  • 147