Add paperclip url to json

你离开我真会死。 提交于 2019-12-30 14:24:33

问题


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


回答1:


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 }



回答2:


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  


来源:https://stackoverflow.com/questions/9650959/add-paperclip-url-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!