我正在制作一个Rails API,在这里我想使用Active Storage将图像附加到帖子,然后能够在REACT中访问它们,例如在JSON中获取url链接。如何将Active Storage映像转换为JSON的URL。有没有一种更好的方法可以获取到帖子图像的链接?
例如,我希望图像URL包含在此信息中:
来自:http://localhost:3001/api/posts
[{"id":8,"title":"lolol","body":"lolol","created_at":"2018-07-19T23:36:27.880Z","updated_at":"2018-07-20T00:17:50.201Z","admin_user_id":1,"post_type":"Song","link":"dgdadg","song_title":"dgdadg","tag_list":[]},{"id":13,"title":"ddd","body":"dd","created_at":"2018-07-20T00:21:39.903Z","updated_at":"2018-07-20T00:21:39.907Z","admin_user_id":1,"post_type":"Song","link":"dddd","song_title":"ddd","tag_list":["Tag"]}]
这是我的后控制器:
class PostsController < ApiController
before_action :set_post, only: [:show, :update, :destroy]
def index
if params[:tag]
@posts = Post.tagged_with(params[:tag])
else
@posts = Post.all
end
render :json => @posts
end
def show
@post
render :json => @post
end
def create
@post = Post.new(post_params)
end
def update
@post.update(post_params)
head :no_content
end
def destroy
@post.destroy
head :no_content
end
private
def post_params
params.require(:post).permit(:title, :body, :song_title, :post_type, :admin_user_id, :link, :tag_list, :image)
end
def set_post
@post = Post.find(params[:id])
end
end
任何建议将不胜感激。
最佳答案
大约在2周前就去过那里,由于完全相同的问题而决定不使用ActiveStorage。您可以使用一些控制器魔术
url_for(@post.image)
喜欢
render :json => @post.merge({image: url_for(@post.image)})
或类似的规定
class Post
def image_url
Rails.application.routes.url_helpers.rails_blob_path(self.image, only_path: true)
end
end
# controller
render :json => @post.as_json(methods: :image_url)
关于ruby-on-rails - 使用JSON通过Rails Active Storage访问React中的图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51434528/