I am developing a simple API for the first time. I have the model like this publisher has_many products and products belongs_to publisher. Currently i am displaying all the products including the their each publisher details.Now i want to have publisher details as a separate resource(i dont want to display publisher details in the first request) in other words in the json output to have an attribute that will carry a link to publisher details.How do i do this?Also if anybody have any more complex sample codes for API development you have done in the past, please share with me, because i am trying to learn more.Thank you very much. Here is what i have.
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 output
[
{
"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"
}
}]
https://github.com/josevalim/active_model_serializers is a popular project for customizing the serialization of activemodel objects