0

I have two models category and sub_category

class Category < ActiveRecord::Base
    has_many :sub_categories

and

class SubCategory < ActiveRecord::Base
    belongs_to :category

now in my sub_category controller i have

@sub_category = SubCategory.paginate(:page => params[:page], :per_page => params[:per_page]).all(:order => 'id ASC')
respond_to do |format|
          format.json { render json: {:sub_category => @sub_category.as_json(:only => [:id, :name, :category_id, :created_at, :updated_at])} }
      end

but i want the category object to which the subcategory belongs_to within this as shown below

    [
    {
    "sub_category":
    [{
    "created_at":"2013-09-25T07:16:53Z",
    "id":2,
    "name":"mobile",
    "updated_at":"2013-09-25T07:19:39Z"
    "category":{"id":1, "name":"gadgets"}
    }]
    }
    ]

How can i do it? Please help me.

1 Answer 1

1

This should work:

@sub_category = Subcategory.paginate(:page => params[:page], :per_page => params[:per_page]).order('id ASC').includes(:category)
respond_to do |format|
  format.json { render json: {:sub_category => @sub_category.as_json(
    :only => [:id, :name, :category_id, :created_at, :updated_at],
    :include => {:category => {:only => [:id, :name])} }
end
Sign up to request clarification or add additional context in comments.

4 Comments

Thankyou, I have been trying this but what i did is :include => [:categories] instead of :include => [:category]. So thankyou anyway.
one more doubt. In category i can use :include => [:sub_categories] but can i able to limit the number of sub_categories to be included. May be we can define it in model but i wanted to limit in only this response. Is this is possible?
@Logesh basically, you can't because of how eager loading works.
ok. Is there some other way to restrict or can i be able to do like this Category.includes(:sub_categories).first or anything similar. Actually I wanted to fetch the categories along with the first sub_category.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.