0
votes

I had set up a default avatar when I set up Carrierwave. It is no longer working. I tried this work around in the view, but it isn't working either. The default is always show, even after the avatar image gets uploaded by the user.

In my view: <% if @avatar.nil? %> <%= link_to image_tag(('/assets/images/default.png').to_s), user %> <% else %> <%= link_to image_tag(user.avatar.to_s, collection: user), user %> <% end %>

user.rb: validates_presence_of :avatar, allow_blank: true

I had also tried this as a workaround but didn't work:

def create
    @user = User.new(user_params)
    #@avatar = "/assets/images/'default.png'"
    if @user.save
      sign_in @user
      flash[:success] = "Welcome!"
      redirect_to :back
    else
       flash[:error] = "Please fill in required information."
       render 'new'
    end
end

session_helper.rb

def avatar_changed?
    @avatar = Avatar.find(params[:id])
    if user && user.read_attribute(:avatar).present?
      user.read_attribute(:avatar)
    else
      user.avatar.recreate_versions!
      avatar.save!
    end
  end

Any suggestions on how I can set it up to have a default image but have it change if/when the user uploads one personally?

Thanks

2
I'm sorry, how can you use both allow_blank and validates_presence_of? Don't you thing it's absolutely different staff?Ivan Shamatov

2 Answers

0
votes

Here is a thread in carrierwave repository. default_url just doesn't work when you use s3. They just didn't make it work.

And here is a possible solution:

  1. move fallback images folder into app/assets/images

  2. change default_url method like this, where ENV['FOG_DIRECTORY'] is the name of your s3 bucket

    def default_url
       image = [version_name, "default.jpg"].compact.join('_')
       "http://s3.amazonaws.com/#{ENV['FOG_DIRECTORY']}/assets/fallback/#{image}"
    end
    

I actually don't have solution for AccessDenied Error, but you can make this bucket public

0
votes

In case anyone else is having a similar issue. I was about to get this to work with the following in my view:

<% if current_user.avatar.present? %>
<%= link_to image_tag(current_user.avatar_url.to_s), current_user %>
<% else %>
<%= link_to image_tag(('/assets/images/default.png').to_s), current_user  %>
<% end %>

Depending on the view I changed the object between if user.avatar.present... and if @avatar.present? I had previously been trying to apply the instance variance (@avatar) universally which was not working.