fydelio
fydelio

Reputation: 953

Rails ActiveStorage url_for returns an URL which is not valid

I have an Employee model with an Avatar. I can attach an image to the avatar, but whenever I try to display the image, the

url_for(@employee.avatar)

produces a dead link. All I'm seeing is the value from the alt attribute from the tag. The image tag I'm getting is the following

<img src="/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBDZz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--4786aa4d9d82d8f8d572b857965088b20fcb2f49/Portrait.jpg" 
alt="Thumbnail">

And I know the image has been properly attached. When I call the following, I get this result:

@employee.avatar
=> #<ActiveStorage::Attached::One:0x00007ff7e9ba41c0 @name="avatar",
@record=#<Employee id: 4, first_name: "Meda", last_name: "Burgdorf",  
created_at: "2019-03-03 23:03:00", updated_at: "2019-03-03 23:17:56">, 
@dependent=:purge_later> 

as I can see the image in the storage directory Screenshot file structure

Help is highly appreciated. Can anyone help me display the saved image.

Here is my setup.

class Employee < ApplicationRecord
   has_one_attached :avatar
   ...
end

Content of my storage.yml file

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

My the migrations from Active Storage are migrated. See my schema.rb file

ActiveRecord::Schema.define(version: 2019_03_03_211537) do

  create_table "active_storage_attachments", force: :cascade do |t|
    t.string "name", null: false
    t.string "record_type", null: false
    t.integer "record_id", null: false
    t.integer "blob_id", null: false
    t.datetime "created_at", null: false
    t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
    t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
  end

  create_table "active_storage_blobs", force: :cascade do |t|
    t.string "key", null: false
    t.string "filename", null: false
    t.string "content_type"
    t.text "metadata"
    t.bigint "byte_size", null: false
    t.string "checksum", null: false
    t.datetime "created_at", null: false
    t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
  end

Upvotes: 9

Views: 3808

Answers (1)

V K Singh
V K Singh

Reputation: 1254

Since Active Storage appends the routes in the master route file, so they come after you catch all the routes. Better you can escape the active storage routes like

get '*path', to: redirect('/'), constraints: lambda { |req|
  req.path.exclude? 'rails/active_storage'
}

Upvotes: 20

Related Questions