0

Normally in html we will use Model.field.url(:thumb) inside image tag, How to do it on json, especially with hash_secret.

flakerimi
  • 2,580
  • 3
  • 29
  • 49

2 Answers2

6

In case of this being helpful to anyone, i find out a nice way to do this:

class MyModel < ActiveRecord::Base
  has_attached_file :avatar, :styles => { :large => "500x500#", :medium => "300x300#", :small => "100x100#", :thumb => "50x50#" }

  def as_json(options)
    json = super
    self.avatar.styles.each do | format |
      json = json.merge({"avatar_"+format[0].to_s => self.avatar(format[0])})
    end
    json
  end
end

You can then simply call

render :json => @my_model

Also working while rendering collections.

It is then possible to do some conditional rendering with as_json(options), with something like:

model_to_json = @my_model.to_json(:nested => true)
render :json => model_json  
nakwa
  • 1,157
  • 1
  • 13
  • 25
2

In your model add the following to get the url (I believe this also works with hashing):

def photo_url_thumb
    photo.url(:thumb)
end 

And then you can output json like this:

 format.json { render :json => @model.photo_url_thumb }
Jayson Lane
  • 2,828
  • 1
  • 24
  • 39