如何解决如何在 ruby 中以 json 形式检索活动存储附件 url
我正在尝试检索活动存储附件的 URL 作为 JSON 响应,但我没有得到正确的响应,这是我的代码:
#projet.rb
def bar[B](f: onSuccess: A => B) =
Try{ some operations } match {
case Success(value) => onSuccess(value)
case Failure(_) => // error handler
}
def funcA = bar(_ => "A")
def funcB = bar(_ => 1)
#projet_serializer.rb
class Projet < ApplicationRecord
has_many :appartements,dependent: :destroy
has_one_attached :image_de_couverture
has_one_attached :situation
has_many_attached :images
end
#projets_controller.rb
class ProjetSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attributes :id,:nom,:gouvernorat,:localite,:surface,:description,:en_cours,:fini,:situation,:images,:image_de_couverture
def images
object.images.map do |image|
rails_blob_path(image,only_path: true) if object.images.attached?
end
end
def image_de_couverture
polymorphic_url(object.image_de_couverture,only_path: true) if
object.image_de_couverture.attached?
end
def situation
polymorphic_url(object.situation,only_path: true) if object.situation.attached?
end
end
这是我使用此代码得到的响应
class ProjetsController < ApplicationController
# show all projects
def index
@projets = Projet.all
render json: @projets
end
def set_projet
@projet = Projet.find(params[:id])
end
def projet_params
params.require(:projet).permit(:nom,images: [])
end
end
代替
[
{
id: 1,nom: "Test",gouvernorat: "Test",localite: "Test",surface: 30303,description: "Test",en_cours: true,fini: true,situation: "/rails/active_storage/blobs/redirect/eyJfcmfpbHMiOnsibWVzc2FnZSI6IkJBaHBFdz09IiwiZXhwIjpudWxsLCJwdXIiOijibG9iX2lkIn19--50589feef3ab662f5fb9877dbf4f0a21c79e2412/lame_rideau1.jpg",images: [
"/rails/active_storage/blobs/redirect/eyJfcmfpbHMiOnsibWVzc2FnZSI6IkJBaHbedz09IiwiZXhwIjpudWxsLCJwdXIiOijibG9iX2lkIn19--0550f31bd4e562c76dfd1aff9f0beac6483e1651/1.jpg","/rails/active_storage/blobs/redirect/eyJfcmfpbHMiOnsibWVzc2FnZSI6IkJBaHBFQT09IiwiZXhwIjpudWxsLCJwdXIiOijibG9iX2lkIn19--11ec06652e38fc43b54ef93187905f4591115d3c/2.jpg",],image_de_couverture: null
},]
我想要附件的链接。
提前致谢。
解决方法
def images
object.images.map do |image|
Rails.application.routes.url_helpers.rails_blob_url(image,only_path: true) if object.images.attached?
end
end
,
尝试通过 rails_blob_path
在您的 rails_blob_url
中更改 ProjetSerializer#images
助手。您还需要在应用程序文件中设置主机配置。 source
# config/application.rb
class Application < Rails::Application
...
routes.default_url_options = { host: 'localhost:3000' }
end
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。