2012-03-05 30 views
2

我使用Rails作爲REST服務器,並且我的一個模型有一個描述字段。在該模型的JSON表示中,我需要輸出常規描述字段和稱爲description_markdown的任意非數據庫屬性,該屬性就是通過降落過濾器運行的描述。我已經知道如何用隆重的接待,像運行通過降價文本:在Rails模型中包含任意字段JSON輸出

@post = Post.find(params[:id]) 
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true, :fenced_code_blocks => true, :lax_html_blocks => true) 
description_markdown = markdown.render(@post.description).html_safe 

但我真正需要的是讓description_markdown上@post屬性(如@ post.description_markdown),並使其在輸出@後的JSON表示。

回答

4

我通常使用RABL gem爲我的API構建JSON視圖 - 它爲構建JSON響應提供了很多靈活性,例如創建自定義子節點,添加任意代碼。一探究竟。 但是,要回答你的問題,你可以覆蓋as_json方法Post包括返回description_markdown。喜歡的東西(未測試):

#post.rb 
class Post < ActiveRecord::Base 

    def description_markdown 
    ... 
    end 
    ... 
    def as_json(options) 
    super(:only => [:attributes_you_want], :methods => [:description_markdown]) 
    end 
    ... 
end 

然後,控制器:

render :json => @post 

希望,它幫助。

2

你可以添加description_markdown到模型:

def description_markdown 
    markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true, :fenced_code_blocks => true, :lax_html_blocks => true) 
    markdown.render(description).html_safe 
end 

然後添加到模型的as_json using :methods

def as_json(options = { }) 
    super((options || { }).merge({ 
     :methods => [:description_markdown] 
    })) 
end 

這將您description_markdown輸出添加到模型的標準JSON表示。 options || { }是在那裏,如果有人給你niloptions,然後我們合併我們的:methods到選項,並把它交給ActiveRecord :: Base爲繁重。如果您希望外部人員能夠發送自己的:methods值,則需要更復雜的options合併。

0

只想添加的情況下,你定義哪些字段/數據您在控制器需要一個替代(就像你可能在Rails應用程序4),像這樣:

Post.to_json(only: [], methods: [:generate_markdown]) 

中發佈您的代碼,加:

def generate_markdown 
    markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true, :fenced_code_blocks => true, :lax_html_blocks => true) 
    return markdown.render(@post.description).html_safe 
相關問題