2014-09-27 53 views
1

我的模型中有一個名爲「file_url(:thumb)」的自定義方法來接收特定的縮略圖文件URL。該方法由載波寶石提供。將虛擬屬性添加到活動記錄對象以輸出

它不存儲在我的數據庫中。我如何將這個虛擬屬性添加到@document,所以當我轉換爲JSON時,它包含在內?

module Api 
    module V1 
    class DocumentsController < ApiController  

     respond_to :json 

     def show 
     @document = Document.find(params[:id]) 
     respond_to do |format| 
      format.json { render json: @document } 
      format.xml { render xml: @document } 
     end 
     end 
    end 
    end 
end 

回答

1

您需要在Document模型中定義自己的as_json方法。像這樣的事情會做的伎倆:

def as_json(options = { }) 
    h = super(options) 
    h[:thumb_url] = file_url(:thumb) 
    h 
end