0

I have a method in events_controller.rb that I want to return a json object that combines data from Object.all and the rails_blob_path of the attached image to each JSON element. The images are not part of the events model but are attached.

class EventsController < ApplicationController

  def get_events
    @events = Event.all
    images = @events.map {|i| rails_blob_path(i.image)}
    render json: { data: @events, images: images}

  end

end

this renders

{"data":[{"id":7,"name":"New York Event","datetime":null,"location":"NYC","tickets":null,"created_at":"2020-06-04T15:21:23.656Z","updated_at":"2020-06-04T15:21:23.712Z","price":null}],"images":["/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBCdz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--ec449cf510b8b7dd19c83531422a4fbe47890f12/nyc.jpeg"]}

but I want "images" to be part of the "data" element so that I can query data.id, data.name and data.image.

Any help is greatly appreciated.

1 Answer 1

1

You can do

@events = Event.all.map { |e| e.attributes.merge(image: rails_blob_path(e.image)) }
render json: { data: @events }, status: 200
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.