0

我有两个模型类别和子类别

class Category < ActiveRecord::Base
    has_many :sub_categories

class SubCategory < ActiveRecord::Base
    belongs_to :category

现在在我的 sub_category 控制器中

@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

但我想要子类别所属的类别对象,如下所示

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

我该怎么做?请帮我。

4

1 回答 1

1

这应该有效:

@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
于 2013-09-27T07:05:20.600 回答