Rails:仅按需解析"has_many"

Rails: Resolve "has_many" only on demand

我仅将 rails 用作后端,以向 Ember 前端应用程序提供 JSON 数据。

我的数据库结构非常串联,导致 rails 在每次请求时加载完整的数据库。

我该如何处理?

比如我得到了博客,博客"has_many"篇,文章"has_many"条评论等等。当我想看博客时,我不关心评论,我只需要文章列表。

那么,当我不需要它们时,如何防止 rails 解析文章上的 "has_many" 关系?

我想我已经找到了解决方案...不确定这是否是最好的方法,但它确实有效...我向控制器添加了一些条件,现在它看起来像:

def index
    @offices = Office.all
    render json: @offices.as_json(
        only: [:id, :title, :created_at],
        include: { 
            addresses: { 
                except: [:contacts] 
            } 
        }
    )
end