0
votes

I'm using CarrierWave uploader for user avatars in my rails project and I'm currently providing a default URL (randomly chosen from 4 choices) for users who didn't upload their pictures. As suggested by the CarrierWave README, I've implemented it as thus:

class UserAvatarUploader < ImageUploader
  def default_url(*args)
    ActionController::Base.helpers.asset_path("avatars/default_avatar_#{rand(4).to_s}.png")
  end
end

Since it is a random function, the problem here is that the user's avatar changes every time the page is reloaded. Ideally I would like to derive a number from the username of the user so that his/her default avatar stays consistent. How might I do that? Thanks in advance!

1
rather than using rand you can use lets say user.id or something if you want it to be unique?uday
@uDaY Yes that would work too. Essentially I just want to get user information from within the default_url method but I don't know how toJin Zhe

1 Answers

1
votes

Ok I solved it. Essentially I was stuck because I couldn't find a way to get user information from within the default_url method. I later found out that the variable model is available and it refers to the user. Here's my final code:

class UserAvatarUploader < ImageUploader
  def default_url(*args)
    number = model.id % 4
    ActionController::Base.helpers.asset_path("avatars/default_avatar_#{number}.png")
  end
end