ruby-on-rails - 在 Rails 模型 JSON 输出中包含任意字段

标签 ruby-on-rails ruby

我使用 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 ,例如创建自定义子节点、添加任意代码。一探究竟。 但是,要回答您的问题,您可能可以覆盖 Postas_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/

相关文章:

ruby-on-rails - :model and @model in form_for?之间的区别

ruby-on-rails - 何时何地聚合或计算 RESTful Rails API 中的数据

regex - 使用正则表达式检查用户输入的开头是否恰好有两个大括号

ruby - 局部变量以下划线开头是好习惯吗?

ruby-on-rails - CanCan、Rails 和协作

ruby-on-rails - 如何在 ruby​​ on rails 中启用开发模式或显示错误

ruby-on-rails - Rails, Attachment_fu - 数据库存储附件的深拷贝

ruby-on-rails - rails 4 : testing GET request on a namespaced controller

css - 在 ruby​​ on rails 或 CSS 中修改文件上传按钮的外观

ruby-on-rails - database.yml &references 不工作