I have 5 images which I want to use as a background at different times (randomly one needs to be chosen to be the background for the body tag). How do I go this, can this be done in the Rails Controller/method or through ERB or through JQuery?
Asked
Active
Viewed 510 times
2 Answers
5
Here's a nice little method of getting a random entry:
random_bg = ['bg1.png', 'bg2.png', 'bg3.png'].shuffle.first
In Ruby 1.9, it's even easier:
random_bg = ['bg1.png', 'bg2.png', 'bg3.png'].sample
I'd put this in your ERB template - it's directly related to the html.

Peter
- 127,331
- 53
- 180
- 211
1
There's no need for jQuery/Javascript to do this. You could do this in either the Controller method or in your ERB template. In either case, you'll have an array of background image file names, and you'll get a random number in the appropriate range, and then set the background image file name to the image whose name is at the randomly chosen location. If you do it in the Controller rather than the template, you'll need to set a variable in your Controller code that contains the image name, so the template can read it.