Ruby-on-rails 如何在 to_json 中获取回形针图像的 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5588185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:52:51  来源:igfitidea点击:

How can I get url for paperclip image in to_json

ruby-on-railspaperclip

提问by Giancarlo Corzo

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'

I'm exporting this model with to_json method and I want to export the image url so I could use it in javascript.

我正在使用 to_json 方法导出此模型,并且我想导出图像 url,以便我可以在 javascript 中使用它。

I know I can access the url like this in the view:

我知道我可以在视图中访问这样的网址:

<%= image_tag model.avatar.url(:medium) %>

But How can I do the same in the to_json method.

但是我如何在 to_json 方法中做同样的事情。

I have some like this:

我有一些这样的:

respond_to do |format|
   render :json => @model.to_json(:only => [:id,:name,:homephone,:cellphone])
end

回答by Ben Zittlau

I believe the easiest way for you to accomplish this will be to create a method in your object to return the avatar URL.

我相信您完成此操作的最简单方法是在您的对象中创建一个方法来返回头像 URL。

class Model < ActiveRecord::Base
    ...

    def avatar_url
        avatar.url(:medium)
    end

    ...
end

This will then allow you to use the methods option when calling to_json with a simple method that does not require any parameters:

这将允许您在使用不需要任何参数的简单方法调用 to_json 时使用 methods 选项:

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:

请参阅这些以供参考:

Ruby to_json :methods arguments

Ruby to_json :methods 参数

http://apidock.com/rails/ActiveRecord/Serialization/to_json

http://apidock.com/rails/ActiveRecord/Serialization/to_json

回答by vinodh

show controller for display image json

用于显示图像 json 的显示控制器

localhost:3000/cities/1.json

本地主机:3000/城市/1.json

respond_to do |format|
  format.html
  format.json { render :json => @model.to_json(:methods => [:model_url]) }
end