user2012677
user2012677

Reputation: 5735

Add Virtual attribute to active record object to output

I have a custom method in my model called "file_url(:thumb)" to receive a specific thumbnail file URL. The method is provided by the carrierwave gem.

It is not stored in my database. How can I add this virtual attribute to @document so when I convert to json it's included?

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

Upvotes: 1

Views: 1021

Answers (1)

Nobita
Nobita

Reputation: 23713

You would need to define your own as_json method in the Document model. Something like this would do the trick:

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

Upvotes: 1

Related Questions