1

In my application I have models Post & Image & I use nested_attributes for Image.

class Post < ActiveRecord::Base
  has_many :images
  accepts_nested_attributes_for :images, reject_if: :all_blank, allow_destroy: true

class Image < ActiveRecord::Base
  belongs_to :post, :counter_cache => true

The purpose of my application is, on each visit/visitor, I only show ONE of the images on that post to user. Currently I just pick a random image.

rnd = @post.images.sample

This works fine, but what I'm looking for is to Distribute visitors based on weight I add to each image.

Default weight can be 10. For instance, I have 6 images on that post & weights are:

Image 1 => weight 10
Image 2 => weight 20
Image 3 => weight 50
Image 4 => weight 30
Image 5 => weight 60
Image 6 => weight 10

What I want to achieve is to distribute visitors to each image based on image weights, so Image 5 would get most of the visitors but we still send visitors to Image 1 & other images.

I haven't yet added weight to images so it can be changed to whatever needed.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Rubioli
  • 685
  • 6
  • 34
  • have a look here: http://stackoverflow.com/questions/4463561/weighted-random-selection-from-array There are multiple solution, depending of performance needs – Doktor OSwaldo Mar 22 '17 at 11:59

1 Answers1

0

I used this gem: weighted_distribution. I ran some tests and it works very good.

Only important thing is that you array, has to look like, which is a hash:

{'object-1' => weight, 'object-2' => weight, 'object-3' => weight, 'object-4' => weight}

My code:

suits = @post.images.pluck(:id, :weight).to_h
Rubioli
  • 685
  • 6
  • 34