2012-03-10 41 views
0

通常在html中,我们将使用Model.field.url(:thumb)内部图像标记,如何在json上执行此操作,特别是使用hash_secret。向json添加回形针url

回答

2

在模型中添加以下,以便获得url(我相信这也与哈希作品):

def photo_url_thumb 
    photo.url(:thumb) 
end 

然后您就可以输出JSON是这样的:

format.json { render :json => @model.photo_url_thumb } 
6

在的情况下,这有助于任何人,我找到一个很好的方式来做到这一点:

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(选项)一些有条件的渲染,喜欢的东西:

model_to_json = @my_model.to_json(:nested => true) 
render :json => model_json