问题
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?
回答1:
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? %>
回答2:
It seems you are missing configuration (because you don't mention it):
You must declare Active Storage services in config/storage.yml
Example from docs:
local:
service: Disk
root: <%= Rails.root.join("storage") %>
test:
service: Disk
root: <%= Rails.root.join("tmp/storage") %>
amazon:
service: S3
access_key_id: ""
secret_access_key: ""
and you must tell Active Storage which service to use by setting Rails.application.config.active_storage.service
Because each environment will likely use a different service, it is recommended to do this on a per-environment basis. To use the disk service from the previous example in the development environment, you would add the following to
config/environments/development.rb
:
# Store files locally.
config.active_storage.service = :local
来源:https://stackoverflow.com/questions/54189616/cant-resolve-image-into-url-to-model-delegated-to-attachment-but-attachment-i