问题
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