fabrik42/acts_as_api

Parent Name under association

reejosamuel opened this issue · 3 comments

Having parent root node name when using associations.

Product.rb

class Product < ActiveRecord::Base
  acts_as_api

  api_accessible :public do |t|
    t.add :name
    t.add :price
    t.add :description
    t.add :image
    t.add :category
  end

  ..... ... 
  belongs_to :category

  .....
end

and the JSON response I get is as follows

{
    "products": [
        {
            "name": "Caesar Salad",
            "price": "40.0",
            "description": "A Caesar salad is a salad of romaine lettuce and croutons dressed with parmesan cheese, lemon juice, olive oil, egg, Worcestershire sauce, garlic, and black pepper. It is often prepared tableside. [source: Wiki]\r\n",
            "image": "/system/products/images/000/000/001/original/caesar-salad-lower.jpg?1377882834",
            "category": {
                "products": {
                    "created_at": "2013-08-30T15:33:13Z",
                    "id": 3,
                    "image_content_type": "image/jpeg",
                    "image_file_name": "salad.jpg",
                    "image_file_size": 295409,
                    "image_updated_at": "2013-08-30T16:55:21Z",
                    "name": "Salads",
                    "primary": null,
                    "updated_at": "2013-08-30T16:55:21Z"
                }
            }
        },
    ]
}

My question is, why am I getting products under category? also need help to get rid of it as it doesn't make sense. My Category.rb doesn't have any api template right now.

 "category": {
                "products": {

Hi!

Seems like more people have this problem. Which Rails version are you using?
It would be great if you would put together a small example app, so I can take a look.
I think it would be helpful if you show me how you render the api response in the controller.

I took some time to look into this. It seems like you have no acts_as_api template defined in your Category model. This confuses the lib :)

Please add a template like this:

class Category < ActiveRecord::Base

  has_many :products

  acts_as_api

  api_accessible :public do |t|
    t.add :id
  end

end

And you should be fine.

Thanks @fabrik42 👍 . That just happened to me.