如何在 to_json 中获取回形针图像的 url [英] How can I get url for paperclip image in to_json
问题描述
我有一个像这样使用回形针的模型:
I have a model that uses paperclip like this:
has_attached_file :avatar, :styles => { :large => "100x100>" , :medium => "50x50>", :small => "20x20>" }, :default_url => '/images/missing-owner_:style.png'
我正在使用 to_json 方法导出此模型,并且我想导出图像 url,以便我可以在 javascript 中使用它.
I'm exporting this model with to_json method and I want to export the image url so I could use it in javascript.
我知道我可以在视图中访问这样的网址:
I know I can access the url like this in the view:
<%= image_tag model.avatar.url(:medium) %>
但是我如何在 to_json 方法中做同样的事情.
But How can I do the same in the to_json method.
我有一些这样的:
respond_to do |format|
render :json => @model.to_json(:only => [:id,:name,:homephone,:cellphone])
end
推荐答案
我相信对您来说,最简单的方法是在您的对象中创建一个方法来返回头像 URL.
I believe the easiest way for you to accomplish this will be to create a method in your object to return the avatar URL.
class Model < ActiveRecord::Base
...
def avatar_url
avatar.url(:medium)
end
...
end
这将允许您在使用不需要任何参数的简单方法调用 to_json 时使用 methods 选项:
This will then allow you to use the methods option when calling to_json with a simple method that does not require any parameters:
respond_to do |format|
render :json => @model.to_json(:only => [:id,:name,:homephone,:cellphone], :methods => [:avatar_url])
end
这应该会产生以下几行的输出:
Which should yield you an output along these lines:
{"id" => 1, "name" => "Cool model", "homephone" => 1234567890, "cellphone" => 0987654321, "avatar_url" => "www.coolsite.com/this_avatars_path"}
请参阅以下内容以供参考:
See these for reference:
http://apidock.com/rails/ActiveRecord/Serialization/to_json
这篇关于如何在 to_json 中获取回形针图像的 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!