将纸夹url添加到json
通常在html中我们将在image标签内部使用Model.field.url(:thumb),如何在json上使用它,特别是使用hash_secret。
在你的模型中添加以下内容以获取url(我相信这也适用于散列):
def photo_url_thumb photo.url(:thumb) end
然后你可以像这样输出json:
format.json { render :json => @model.photo_url_thumb }
如果这对任何人都有帮助,我会找到一个很好的方法来做到这一点:
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
然后你可以简单地打电话
render :json => @my_model
同时在渲染集合时工作。
然后可以使用as_json(options)进行一些条件渲染,例如:
model_to_json = @my_model.to_json(:nested => true) render :json => model_json