Rails ActiveStorage url_for returns an URL which is not valid

十年热恋 提交于 2019-12-10 19:28:27

问题


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

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

回答1:


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'
}



回答2:


Removing the generic routes path from routes.rb resolved the broken-URL problem with the images.

#get '*path' => redirect('/')  #removed this line

Presumably the routes from the Active Storage engine are appended to the master route list so they come after your catch-all route



来源:https://stackoverflow.com/questions/54990363/rails-activestorage-url-for-returns-an-url-which-is-not-valid

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