Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access images in React through Rails Active Storage using JSON

I'm making a Rails API where I would like to use Active Storage to attach images to posts and then be able to access them in REACT, such as getting the url link in JSON. How do I convert the Active Storage images to urls for JSON. Is there a better way to be able to get the link to the images for the posts?

For example, I would want the image url to be included in this information:

From: 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"]}]

Here is my Post Controller :

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

Any suggestions would be greatly appreciated.

like image 940
Alex Erling Avatar asked Jul 20 '18 03:07

Alex Erling


2 Answers

Have been there like 2 weeks ago and decided against ActiveStorage because of the exact same issue. You can do some controller magic that uses

url_for(@post.image)

like

render :json => @post.merge({image: url_for(@post.image)})

or something along those lines

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)
like image 57
Denny Mueller Avatar answered Nov 08 '22 14:11

Denny Mueller


It's possible within jbuilder to access the url_for helper. So your _post.json.jbuilder could work something like this

json.extract! post, :id, :body, :created_at, :updated_at
if post.image.attached?
  json.image_url url_for(post.image)
end
json.url product_url(product, format: :json)
like image 1
rissem Avatar answered Nov 08 '22 14:11

rissem