rails - Displaying image in view after uploading a file via Active Storage

穿精又带淫゛_ 提交于 2019-12-10 12:49:36

问题


I have a project that is on rails 5.1.2 and I am trying to implement Active Storage on it, following couple of tutorials online I am able to setup the Active Storage and I can see the data being saved inside the active_storage_blobs and active_storage_attachments table.

  1. Tutorial 1
  2. Tutorial 2

I also confirmed by running user.avatar.attached? and in response I got true so things are working.

What I am having problem with is displaying an image in view, I have tried

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

NoMethodError: undefined method `active_storage_attachment_path'

What I have done to setup Active Storage

Ran the install command

rails active_storage:install

This gave error Don't know how to build task 'active_storage:install'

but the following command worked

rails activestorage:install

I have added gem 'activestorage' inside gemfile

This is what I have inside my storage_services.yml

test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

Inside my development.rb I have added

config.active_storage.service = :local

Inside my User model I have added has_one_attached :avatar

Inside the controller on update I added the attachment code

user.avatar.attach(params[:user][:avatar])
  1. I can see the image being added in database,
  2. I can see the image being saved in the storage directory on root

Yet I am not able to display it,

What am I missing here? What do I need to do to get the image to display in the view? Why am i getting this error

NoMethodError: undefined method `active_storage_attachment_path'


回答1:


Can you check your config/appication.rb file if you have added this line:

require "active_storage/engine"

I would recommend you to upgrade your rails version to 5.2 beta as it has merged with Active Storage gem. If your application is covered with a good coverage of tests you can do it now. There are not so many changes from 5.1 to 5.2 see http://edgeguides.rubyonrails.org/5_2_release_notes.html .But it is not yet stable so you need to check if you can take that risk.



来源:https://stackoverflow.com/questions/46971979/rails-displaying-image-in-view-after-uploading-a-file-via-active-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!