ruby-on-rails - 渲染 json 中的 Rails Active Storage 图像链接

标签 ruby-on-rails rails-activestorage

我怎么能用我的帖子(每个帖子都有一个附件)和他们的图片网址渲染一个json?

def index
  @posts = Post.all
  render json: { posts: @posts }, include: :image # Image is the attachment
end

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

最佳答案

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

app/view/posts/index.json.jbuilder


json.array! @posts, partial: 'post', as: :post

app/view/posts/_post.json.jbuilder


json.id post.id
json.image_url url_for(post.image) if post.image.attached?
//all other fields you need

关于ruby-on-rails - 渲染 json 中的 Rails Active Storage 图像链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52839294/

相关文章:

ruby-on-rails - 如何在一个葡萄 block 中创建两条路线?

ruby-on-rails - Rails 6 和 TailwindCSS 的 PostCSS 插件错误

ruby-on-rails - 为什么我的根节点最终将自己作为带有acts_as_tree 的parent_id?

ruby-on-rails - Rails 5.2 credentials.yaml.enc 和 master.key 不适用于 Heroku

ruby-on-rails - 尝试使用heroku上的rails应用程序从S3获取图像时出现ERR_CERT_COMMON_NAME_INVALID

ruby-on-rails - 如何修复错误 URI(不是 URI?): nil

ruby-on-rails - Ruby on Rails - 我如何将页面顶部显示的帖子顺序更改为最新?

ruby-on-rails - PostgreSQL 查找记录并按左外连接排序

ruby-on-rails - ActiveStorage CSV 文件强制编码?

ruby-on-rails - ActiveStorage Analyzer 作业延迟太高