37

I have a model that uses paperclip like this:

has_attached_file :avatar, :styles => { :large => "100x100>" , :medium => "50x50>", :small => "20x20>" },  :default_url => '/images/missing-owner_:style.png'

I'm exporting this model with to_json method and I want to export the image url so I could use it in javascript.

I know I can access the url like this in the view:

<%= image_tag model.avatar.url(:medium) %>

But How can I do the same in the to_json method.

I have some like this:

respond_to do |format|
   render :json => @model.to_json(:only => [:id,:name,:homephone,:cellphone])
end
Giancarlo Corzo
  • 1,976
  • 5
  • 24
  • 36

2 Answers2

61

I believe the easiest way for you to accomplish this will be to create a method in your object to return the avatar URL.

class Model < ActiveRecord::Base
    ...

    def avatar_url
        avatar.url(:medium)
    end

    ...
end

This will then allow you to use the methods option when calling to_json with a simple method that does not require any parameters:

respond_to do |format|
   render :json => @model.to_json(:only => [:id,:name,:homephone,:cellphone], :methods => [:avatar_url])
end

Which should yield you an output along these lines:

{"id" => 1, "name" => "Cool model", "homephone" => 1234567890, "cellphone" => 0987654321, "avatar_url" => "www.coolsite.com/this_avatars_path"}

See these for reference:

Ruby to_json :methods arguments

http://apidock.com/rails/ActiveRecord/Serialization/to_json

Community
  • 1
  • 1
Ben Zittlau
  • 2,345
  • 1
  • 21
  • 30
  • 2
    Example suggests that avatar_url returns absolute url, while it returns relative one. If you need absolute url look at http://stackoverflow.com/a/12556347/257443 . – ciastek Sep 19 '13 at 15:33
  • This works on collections too! (e.g. `@models.to_json(methods: [:example])` – collimarco Nov 01 '15 at 10:03
  • Isn't this too much writing? What if you need like 4 different sizes of the image on 5 different models, do you need to write a method for each? Can't it just return all image sizes paperclip has? – Vedmant Nov 06 '18 at 10:14
  • You can use it like that for render all the sizes `def avatar_url [ medium: avatar.url(:medium), original: avatar.url ] end` – Astm Oct 25 '20 at 11:41
1

show controller for display image json

localhost:3000/cities/1.json

respond_to do |format|
  format.html
  format.json { render :json => @model.to_json(:methods => [:model_url]) }
end
maletor
  • 7,072
  • 7
  • 42
  • 63
vinodh
  • 2,114
  • 1
  • 12
  • 17