2012-10-24 45 views
0

我有一個控制器responds_tohtml和PNG(我動態加載圖像,並將其呈現爲文本)。這使控制器代碼混亂,今天我發現respond_with,看起來非常酷,但我不知道如何使它與格式不同,比html,json和xml(如PNG)Ruby on Rails的respond_with和圖像格式

我期待這會工作,但它劇照試圖找到一個模板文件,而忽略我的方法:(

型號/ user.rb

class User < ActiveRecord::Base 
    def to_png 
    File.read("some_file.png") 
    end 
end 

控制器/ users_controller.rb

class UsersController < ApplicationController 
    respond_to :html, :png 

    # GET /users/1 
    def show 
    @user = User.find(params[:id]) 
    respond_with(@user) 
    end 
end 

回答

2

嘗試在文件中添加[YOUR_APP]/config/initializers/mime_types.rb

Mime::Type.register "image/png", :png 

,並重新啓動應用程序

1

,如果你需要使用的默認情況下不支持的MIME類型,你可以 註冊在environment.rb中的自己的處理程序如下。

Mime::Type.register "image/jpg", :jpg

http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to

在environment.rb中

Mime::Type.register "image/png", :png 

然後

respond_to do |format| 
    format.png do 
     #do stuff here 
    end 
end 

respond_with @user do |format| 
    format.png do 
     #do stuff here 
    end 
end 
+0

我嘗試了MIME類型註冊,但它仍然給我「模板丟失」 我知道respond_to然後format.png將工作,因爲它目前是這樣的,但我希望它可以被移動模型如to_json和to_xml,以便控制器只能調用respond_with –