Rails: Paperclip with multiple placeholder images?

左心房为你撑大大i 提交于 2019-12-24 11:28:11

问题


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!


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/6362026/rails-paperclip-with-multiple-placeholder-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!