Search code examples
ruby-on-railsformsmodelrails-activestorage

Can't resolve image into URL: to_model delegated to attachment, but attachment is nil in Rails 5.2


I have the following form:

<%= form_with(model: user, local: true) do |form| %>
  <% if user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(user.errors.count, "error") %> prohibited this user from being saved:</h2>

      <ul>
      <% user.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.file_field :avatar %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

It is being called on my edit page:

<h1>Upload Avatar</h1>
  <%= image_tag(@user.avatar) %>
  <%= render 'form', user: @user %>
<hr>

I get the error in the title but I am not sure why the avatar is not being attachd to the user model. I have all the requirements done for active_storage.

has_one_attached :avatar in user model.

In user controller:

  def identity_params
    params.permit(:email_confirmation, :password, :password_confirmation, :avatar).to_h.symbolize_keys.tap do |params|
      params[:email] = params[:email_confirmation]
    end 
  end 

Also I have all the necessary migrations. Am I missing the actual avatar attaching logic?


Solution

  • You can get the error message "Can't resolve image into URL: to_model delegated to attachment, but attachment is nil" if you are trying to show in your view an attachment that does not exist:

    <%= image_tag(@user.avatar) %>
    

    to avoid error you should do this:

    <%= image_tag(@user.avatar) if @user.avatar.attached? %>