Rails 5 - 包括无效的嵌套关联

Rails 5 - include nested associations not working

我有两个简单的模型:

  1. note.rb

:title -> string, :content -> string has_and_belongs_to_many :tags, join_table: :tags_notes accepts_nested_attributes_for :tags

  1. tag.rb

:name -> string has_and_belongs_to_many :notes, join_table: :tags_notes

两个模型通过 has_and_belongs_to_many 关系连接。 如上所示,关联 table 称为 tags_notes。 好吧,我这里的问题是,在我的 RESTful 控制器中,要获取注释,我有这个:

获取/api/notes 这只有 returns 注释对象:

[
    {
        "id": 1,
        "title": "12231",
        "content": "121213"
    },
    {
        "id": 2,
        "title": "test",
        "content": "testtest"
    }
]

但是,每个注释都有 tags,我也想将它们转储到响应中,如下所示:

     [
        {
            "id": 1,
            "title": "12231",
            "content": "121213",
            tags: [
              {
                 "name": "test",
                 "id": 1
              },
              { 
                ...
              } 
            ]

        },
         ...
    ]

在我的控制器中,我试过了 Note.includes(:tags).

当前控制器代码: def index notes = Note.includes(:tags) render json: notes, status: :ok end

他们似乎只 return notes,没有 tagsNote.eager_load(:tags) 我做错了什么?找不到足够的文档来帮助我解决此问题。 如果有人可以帮助我,我将不胜感激。

非常感谢。

在发布我的问题后不久,我自己找到了答案。 include 必须进入 render.

所以控制器代码

  def index
    notes = Note.all
    render json: notes, :include => :tags, status: :ok
  end

似乎可以解决问题![​​=13=]