变体委派给附件,但附件为nil

时间:2019-06-16 22:47:37

标签: ruby-on-rails rails-activestorage

我正在使用ActiveStorage开发Rails 6应用程序。我正在使用devise进行身份验证,这需要在sign_up页面上输入电子邮件和密码。成功注册后,我想重定向到编辑个人资料。用户不一定需要上传头像或其他一些字段。如果用户选择的话,可以将其保留为空。

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>

我收到以下错误,但是我希望这些字段是可选的,如何实现呢? 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 %>

我有以下表格。如果没有上传头像,请不要在show.html.erb页面中抛出nil错误。

1 个答案:

答案 0 :(得分:1)

您用attached?

检查
<% if @user.avatar.attached? %>
  <%= image_tag @user.avatar.variant(resize_to_limit: [100, 100])%>
<% end %>