Filippo Luppi
Filippo Luppi

Reputation: 75

Rails respond with paperclip image.url multiple URLs

I'm building a simple rails application where users can upload some images. Now I need a simple controller that returns the image's URLs of related record which have the same id_attivita. To do so I create a function in the controller and enable it in the routes.rb file.

My question is about how to respond to the http request with the attribute value of image.url provided from paperclip?

    def getattached
      @photo_attivitum = PhotoAttivitum.where(id_attivita: params[:id_attivita])
                                       
    
     respond_to do |format|
       
     @photo_attivitum.each do |p|
        format.html { render :json => p.image.url}
      end
    end
  end

it works but it returns only the URLs of the first record not the other four record's URLs... How can I do this?

Upvotes: 0

Views: 197

Answers (2)

praga2050
praga2050

Reputation: 773

Add the following gem to your Gemfile

gem 'active_model_serializers'

Then install it using bundle

bundle install

You can generate a serializer as follows

rails g serializer photo_attivitum

it will create Serializer class file in

# app/serializers/photo_attivitum_serializer.rb

class PhotoAttivitumSerializer < ActiveModel::Serializer
   attributes :id, :image_url

   def image_url
     object.image.url
   end 
end

And in controller

def getattached
  @photo_attivitum = PhotoAttivitum.where(id_attivita: 
   params[:id_attivita])


  render json: @photo_attivitum
end

Upvotes: 1

Imre Raudsepp
Imre Raudsepp

Reputation: 1178

Not sure what u want to do? Show all image urls in json?

    urls = @photo_attivitum.pluck('image_url')
    format.html { render :json => urls}

Upvotes: 0

Related Questions