【问题标题】:Customize json output in Rails rest API with to_json使用 to_json 在 Rails REST API 中自定义 json 输出
【发布时间】:2012-11-14 16:44:59
【问题描述】:

我是第一次开发一个简单的 API。我有这样的模型publisher has_many productsproducts belongs_to publisher。目前我正在显示所有产品,包括他们的每个发布者详细信息。现在我希望将发布者详细信息作为单独的资源(我不想在第一个请求中显示发布者详细信息),换句话说,在 json 输出中具有一个属性将带有发布者详细信息的链接。我该怎么做?另外,如果有人有你过去做过的更复杂的 API 开发示例代码,请与我分享,因为我正在努力学习更多。非常感谢.这是我所拥有的。

产品控制器

 respond_to :json, :xml
 def index
 @products=Product.paginate(:page=>params[:page],:per_page => params[:per_page]).all(:include =>  :publisher)
  respond_to do |format|
  format.json { render json: @products.to_json(
    :include=>:publisher) }
  format.xml
   end
   end

json 输出

    [

 {
    "category_id": null,
    "created_at": "2011-03-25T13:35:16Z",
    "details": "Molestias pariatur consequuntur ut voluptas aperiam facere et et autem ad laudantium ut qui dolorem iste sit ut in dignissimos. Et debitis et et sunt quidem qui est est et",
    "id": 1,
    "product_name": "Velit",
    "publisher_id": 1,
    "updated_at": "2012-11-12T18:45:13Z",
    "publisher": {
        "created_at": "2012-11-12T18:45:13Z",
        "email": "ibrahim@greenholt.net",
        "id": 1,
        "password": "Madelyn Parker",
        "password_confirmation": null,
        "publisher_id": null,
        "updated_at": "2012-11-12T18:45:13Z"
    }
}]

【问题讨论】:

  • 谢谢,但我想按照传统方式使用 to_json。
  • 支持我的声明:blog.gomiso.com/2011/05/16/…
  • 是的,我知道那个博客,但我没有说明如何解决我的问题。

标签: ruby-on-rails ruby-on-rails-3 json api rest


【解决方案1】:

https://github.com/josevalim/active_model_serializers是一个流行的项目,用于自定义activemodel对象的序列化

【讨论】:

  • 我不能用 to_json/as_json 做这个吗?
  • activemodel 序列化器有一些替代品
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-07
  • 2021-10-31
  • 1970-01-01
  • 2012-02-09
  • 1970-01-01
  • 2020-03-01
  • 2011-03-13
相关资源
最近更新 更多