I’m creating an application that’ll display a random picture based upon a defined letter in a word.
Images are attached to a Pictures model (containing another “letter” field) using Paperclip, and will be iterated through in an each block.
How would I go about passing the letter back from the each block to the model for random selection.
This is what I’ve come up with so far, but it’s throwing the following error.
undefined method `%' for {:letter=>"e"}:Hash
Model:
def self.random(letter)
if (c = count) != 0
find(:first, :conditions => [:letter => letter], :offset =>rand(c))
end
end
View:
<% @letters.each do |a| %>
<%= Picture.random(a).image(:thumb) %>
<% end %>
Thanks
One problem is your conditions has a syntax error. The hash notation is wrong:
should be
Also, it seems to me that your random scope will always exclude the first Picture if you don’t allow an offset of 0. Besides that, do you really want to return nil if the random number was 0?
Picture.random(a).image(:thumb) would throw “undefined method ‘image’ for nil:NilClass” exception every time c==0. Can probably just use:
EDIT: You’ll either need to guarantee that your db has images for all letters, or tell the user no image exists for a given letter.
Or the like…
EDIT: Actually I don’t think your offset strategy will work. One other approach would be to return the set of images available for the given letter and randomly select from that collection, something like: