使用JSON API呈现所有级别的递归关联

时间:2019-04-01 02:50:42

标签: ruby-on-rails rails-api

  • 一个类别可以具有一个或多个类别
  • 一个类别属于(可选)一个类别

    def index
      @categories = Category.all
    
      render json: @categories, include: 'categories.**', only: [:name, :category_id]
    end
    

此代码仅呈现一个关联级别:

[
{
    "name": "any1",
    "category_id": null,
    "categories": [
        {
            "id": 13,
            "name": "any2",
            "created_at": "2019-04-01T02:21:02.258Z",
            "updated_at": "2019-04-01T02:21:02.258Z",
            "category_id": 12
        }
    ]
},
{
    "name": "any2",
    "category_id": 12,
    "categories": [
        {
            "id": 14,
            "name": "any3",
            "created_at": "2019-04-01T02:21:48.600Z",
            "updated_at": "2019-04-01T02:21:48.600Z",
            "category_id": 13
        }
    ]
},
{
    "name": "any3",
    "category_id": 13,
    "categories": []
}

]

理想情况下,根据Rails Api Documentation,我可以在“ any2”中获取“ any3”,我可以通过为一个级别添加“ categories。*”或为所有关联添加“。**”来实现,但似乎没有工作。

render json: @categories, include: 'categories.**', only: [:name, :category_id]

错误是

NoMethodError (undefined method `categories.*' for # 
<Category:0x00007fae0c950ff8>

category.rb

class Category < ApplicationRecord
  belongs_to :category, :class_name => 'Category', optional: true
  has_many :categories, :class_name => 'Category', :foreign_key => 'category_id'

  accepts_nested_attributes_for :category
end

0 个答案:

没有答案