0
votes

I use Rails as a backend and React as a frontend.

I upload photos of meals via Carrierwave to my AWS S3 bucket.

When I do so, here is what I get from the rails console:

m = Meal.first
[...]
m.photo
=> #<PhotoUploader:0x007fef8e4381b0 @model=#<Meal id: 1, name: "Burger Caviar", price: "5.99", original_price: "8.90", description: "Delicieux Burger, parfume au caviar d'aubergine et...", ingredients: "Pain, steack de boeuf, caviar, salade, tomates, oi...", allergenes: "aucun", category: "Français", week_day: 1, photo: "Photo_May_21_11_45_12_PM_1024x1024.jpg", vacation_mode: false, restaurant_id: 1, created_at: "2018-11-06 13:00:46", updated_at: "2018-11-06 13:00:46">, @mounted_as=:photo, @file=#<CarrierWave::Storage::Fog::File:0x007fef8e433c50 @uploader=#<PhotoUploader:0x007fef8e4381b0 ...>, @base=#<CarrierWave::Storage::Fog:0x007fef8e433ea8 @uploader=#<PhotoUploader:0x007fef8e4381b0 ...>>, @path="uploads/Photo_May_21_11_45_12_PM_1024x1024.jpg", @content_type=nil>, @filename=nil, @cache_id=nil, @versions={}, @storage=#<CarrierWave::Storage::Fog:0x007fef8e433ea8 @uploader=#<PhotoUploader:0x007fef8e4381b0 ...>>>

m.photo.path
=> "uploads/Photo_May_21_11_45_12_PM_1024x1024.jpg"

m.photo.url
=> "https://take-a-meal-images.s3.amazonaws.com/uploads/Photo_May_21_11_45_12_PM_1024x1024.jpg"

I actually need m.photo.path to serve my image (via imgix) to the client in React. However, when I call my meals via axios and console.log the response, all I get is the photo URL:

data: Array(9)
[...]
0:
  created_at: "2018-11-06T14:00:49.373+01:00"
  id: 10
  name: "Burger Nordiste"
  photo:
      url: "https://take-a-meal-images.s3.amazonaws.com/uploads/header-image.jpg"
[...]

My controllers/meals_controller.rb:

class MealsController < ApplicationController
  def index
    @meals = Meal.all
    render json: @meals.to_json(include: :restaurant)
  end
end

so why does rails only serve photo.url and how can I change that in order to access photo.path in React ?

1
It looks like carrierwave specifically exports the url[1]. You'll likely need to create a new serializer to include additional attributes. [1]: git.io/fpvx6Baylor Rae'
Hi @BaylorRae', thank you very much for your help. I actually do not really understand what a serializer is and in my case how I can solve my issue...Uj Corb

1 Answers

1
votes

The easiest solution to override the default serializer for an uploader is to overload the serializable_hash method inside your uploader.

If this is an overload you need to apply often I would recommend creating a module/concern to avoid duplication.

# app/uploaders/photo_uploader.rb
class PhotoUploader < CarrierWave::Uploader::Base
  # existing code...

  def serializable_hash(*args)
    super(*args).merge({'path': path})
  end
end