简体   繁体   中英

Rails: Paperclip with multiple placeholder images?

I've been trying to experiment with having avatars for users in my app, and I've set this up where a user can upload an image using Paperclip. Paperclip has a nice default functionality where you can define a placeholder image when the user has not uploaded an image. What I'm wondering is, is there any way to create a set of placeholder images and have paperclip choose one at random when the associated record is created? IE so not all the "no avatar" icons have to be identical?

Thanks!

My best guess for how to accomplish this would be to "override" how you access your avatar images.

Maybe something along the following:

 module UserHelper

   def avatar_url(user)
     user.avatar ? user.avatar.url : random_avatar_url
   end

   def random_avatar_url
     ...
   end

 end

This way you can use one interface to access the existing avatar or a randomly chosen one from your views. You don't want to use random_avatar_url directly from your views, so maybe private or protect it to make sure others know.

class User
  def avatar_image
   avatar.exists? ? avatar.url : "path_to_placeholder_image"
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM