繁体   English   中英

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关系连接。 如上所述,该关联表称为tags_notes 好吧,我这里的问题是,在我的RESTful控制器中,要获得注释,我有这个问题:

GET /api/notes这仅返回Note对象:

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

但是,每个注释都有tags ,我也想在响应中转储这些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

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

谢谢你

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

所以控制器代码

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

似乎可以解决问题!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM