TopperH
TopperH

Reputation: 2223

Chose a random paperclip attachment

I have "foo" controller that, among other things has 3 paperclip attached images.

foo.image1, foo.image2 and foo.image3

What is the best way to render in a view one random attachment that gets refreshed every time the page is reloaded?

--EDIT---

Ok, this is not very elegant code but at least avoids using send and serves my purpose.

    @a = foo.image1(:thumb) 
    @b = foo.image2(:thumb)
    @c = foo.image3(:thumb)

    @rand = ([@a, @b, @c].sample)

Upvotes: 0

Views: 68

Answers (1)

MrDanA
MrDanA

Reputation: 11647

In your controller you can do something like:

@image = foo.send([:image1, :image2, :image3].sample)

What this is doing is randomly selecting (sampling) a symbol corresponding to the name of the images, and then sending that symbol to foo to execute. The result is stored in the instance variable, which can then be used in your view.

As long as this is done every time someone hits your action (e.g if it's in a show action or something) then it will always randomly select a new image, even on refresh.

Upvotes: 1

Related Questions