包括模型中的模型关联

Include model associations from within the model

我需要清理我的代码使用:

# class ProjectsController < ApiController
def show
  render json: Project.find_by(id: params[:id]).as_json(include: :user)
end

至:

render json: Project.find_by(id: params[:id]) // should include the association

有没有办法将此逻辑放入模型中?我正在使用 Rails 5 API

class Project < ApplicationRecord
  belongs_to :user, include: :project // I thought this would work

  def self.foo
    self.includes(:user)
  end
end

# in controller
render json: Project.foo.find_by(id: params[:id]) // nothing

如果 Project 属于许多模型并且需要仅通过调用 Project.find(1) 来包含它怎么办,我将在我的控制器中嵌套一些 includes。我可以将所有这些逻辑放入模型中,然后 Project.find(1) 会以 json 格式显示所有关联吗?

在您的项目模型中,覆盖 as_json 方法以包含关联 user:

def as_json(options = {})
  super(include: :user)
end