简体   繁体   English

将虚拟属性添加到活动记录对象以输出

[英]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. 我的模型中有一个自定义方法,称为“ file_url(:thumb)”,用于接收特定的缩略图文件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? 如何将这个虚拟属性添加到@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

You would need to define your own as_json method in the Document model. 您将需要在Document模型中定义自己的as_json方法。 Something like this would do the trick: 这样的事情可以解决问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM