Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variant delegated to attachment, but attachment is nil

I'm working on a Rails 6 application using ActiveStorage. I'm using devise for authentication which requires on the sign_up page an email and a password. After successfully sign up I would like to redirect to edit profile. A user doesn't necessarily need to upload an avatar or some of the other fields. Those can be left as empty if that is the choice of the user.

ActionView::Template::Error (variant delegated to attachment, but attachment is nil):
    3: 
    4: <p><%= @user.full_name %><p>
    5: <p>
    6:   <%= image_tag @user.avatar.variant(resize_to_limit: [100, 100])%>
    7: <p>
    8: <p><%= @user.city %><p>
    9: <p><%= @user.bio %><p>

I get the following error but I would like for those fields to be optional, how can I achieve this? users/edit.html.erb

  <%= form_for @user do |f| %>
    <div class="form-group">
      <%= f.label :avatar %>
      <%= f.file_field :avatar, as: :file, class: "form-control" %>
    </div>

    <div class="form-group">
      <%= f.label :full_name, 'Full Name' %>
      <%= f.text_field :full_name, autofocus: true, class: "form-control" %>
    </div>

    <div class="form-group">
      <%= f.label :city, 'City' %>
      <%= f.text_field :city, class: "form-control" %>
    </div>

    <div class="form-group">
      <%= f.label :bio, 'Bio'%>
        <p> Why did you join ArtsySpace?
        What should other people here know about you?
        </p>
      <%= f.text_field :bio, class: "form-control"%>
    </div>

    <div class="form-group">
      <%= f.submit "Edit profile", class: "btn btn-primary" %>
    </div>
  <% end %>

I have the following form. I would like that if no avatar is uploaded to not throw the nil error in the show.html.erb page.

like image 406
Steven Aguilar Avatar asked Jun 16 '19 22:06

Steven Aguilar


1 Answers

You check for this with attached?

<% if @user.avatar.attached? %>
  <%= image_tag @user.avatar.variant(resize_to_limit: [100, 100])%>
<% end %>
like image 64
Eyeslandic Avatar answered Oct 17 '22 10:10

Eyeslandic