Returning a 1x1 .gif as a response in Rails
I'm building a Rails app that does conversion tracking on outside sites. I'd like to allow users to paste an image tag in their conversion pages (like AdWords), and whenever that image is requested, a conversion registers in my app.
respond_to do |format|
开发者_JS百科 if @conversion.save
flash[:notice] = 'Conversion was successfully created.'
format.html { redirect_to(@conversion) }
format.xml { render :xml => @conversion, :status => :created, :location => @conversion }
format.js { render :json => @conversion, :status => :created }
format.gif { head :status => :ok }
else
format.html { render :action => "new" }
format.xml { render :xml => @conversion.errors, :status => :unprocessable_entity }
end
end
This way, the browser gets a non-existent .gif image. Is there a better way to do this?
This seems to be a simpler solution
Source:
http://forrst.com/posts/Render_a_1x1_Transparent_GIF_with_Rails-eV4
instead of rendering, call
send_data(Base64.decode64("R0lGODlhAQABAPAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="), :type => "image/gif", :disposition => "inline")
Simple option:
format.gif { redirect_to '/images/1x1.gif' }
I think in /really/ old browsers (IE5, Netscape maybe?) this may not work, so if you need to support those, the old school solution was to actually load in the binary data of the gif and spit it out back to the browser directly with the correct content type.
Here is my solution
format.gif { send_data Rails.root.join('app', 'assets', 'images', '1x1.gif') }
精彩评论