Search code examples
ruby-on-railsrubyactiverecordphotoseed

Rails, active storage, attach_one photo, doesn't work when fetching photo from folder


So I am trying to attach a picture to an instance of my database, but I can't find the correct path syntax to fetch it from my images folder. What am I doing wrong?

It works fine when I host an image on my server with this syntax:

bar1.photo.attach(io: URI.open("https://www.ogsoundfx.com/ogcoding/photo_test/image1.jpg"), filename: 'bar1')

But this doesn't work:

bar1.photo.attach(io: File.open('../../app/assets/images/bar1.jpg'), filename: 'bar1')

Here is a capture of the seed.rg file from where I am running this code: enter image description here

Is my path wrong? To be honest I tried every possible way I could think of, but never made it work. Thanks!


Solution

  • Probably what you want is Rails.root. As you can see in this api documentation this method returns a Pathname object which handles paths starting with a / as absolute (starting from the root of the filesystem).

    bar1.photo.attach(io: File.open(File.join(Rails.root,'app/assets/images/bar1.jpg')), filename: 'bar1')  
    

    This should solve your question.