使用to_json在Rails rest API中自定义json输出

时间:2012-11-14 16:45:00

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

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

的ProductsController

 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"
    }
}]

1 个答案:

答案 0 :(得分:1)

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