我使用 Rails 作为 REST 服务器,我的一个模型有一个描述字段。在该模型的 JSON 表示中,我需要输出常规描述字段和一个名为 description_markdown 的任意非 DB 属性,它只是通过 Markdown 过滤器运行的描述。我已经知道如何使用 redcarpet 通过 markdown 运行文本,例如:
@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),并以@post 的 JSON 表示形式输出。
最佳答案
我通常使用 RABL gem 为我的 API 构建 JSON View ——它为您构建 JSON 响应提供了很大的灵 active ,例如创建自定义子节点、添加任意代码。一探究竟。
但是,要回答您的问题,您可能可以覆盖 Post
的 as_json
方法以包含 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
然后,在 Controller 中:
render :json => @post
希望对您有所帮助。
关于ruby-on-rails - 在 Rails 模型 JSON 输出中包含任意字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9570151/