Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

ruby on rails - 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'

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) %>

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

I have some like this:

respond_to do |format|
   render :json => @model.to_json(:only => [:id,:name,:homephone,:cellphone])
end
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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:

Ruby to_json :methods arguments

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...