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
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)