渲染 json 中的 Rails Active Storage 图像链接

Ric*_*ana 5 ruby-on-rails rails-activestorage

我怎样才能用我的帖子(每个帖子都有一个附件)及其图像网址来渲染 json?

def index
  @posts = Post.all
  render json: { posts: @posts }, include: :image # Image is the attachment
end
Run Code Online (Sandbox Code Playgroud)

我有这个,但我知道这行不通,因为我需要图像 URL

Sik*_*riq 6

json.jbuilder 查看文件可以在这里提供帮助

应用程序/视图/帖子/index.json.jbuilder

json.array! @posts, partial: 'post', as: :post
Run Code Online (Sandbox Code Playgroud)

应用程序/视图/帖子/_post.json.jbuilder

json.id post.id
json.image_url url_for(post.image) if post.image.attached?
//all other fields you need
Run Code Online (Sandbox Code Playgroud)

  • 如果你们想要完整的路径,请使用“rails_blob_url(post.image)”,因为“url_for(post.image)”在生成的网址中没有给出主机名 (2认同)