Ruby on rails 包括模型中的模型关联

Ruby on rails 包括模型中的模型关联,ruby-on-rails,ruby-on-rails-5,rails-api,Ruby On Rails,Ruby On Rails 5,Rails Api,我需要清理我的代码,避免使用: # class ProjectsController < ApiController def show render json: Project.find_by(id: params[:id]).as_json(include: :user) end 有没有办法把这种逻辑放在模型中?我正在使用Rails5API class Project < ApplicationRecord belongs_to :user, include: :proj

我需要清理我的代码,避免使用:

# class ProjectsController < ApiController
def show
  render json: Project.find_by(id: params[:id]).as_json(include: :user)
end
有没有办法把这种逻辑放在模型中?我正在使用Rails5API

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就可以包含它。查找(1)
,我的控制器中将有一些嵌套的
includes
。我是否可以将所有这些逻辑放在模型中,然后
项目。find(1)
将以json格式显示所有关联?

在项目模型中,重写
as_json
方法以包含关联
用户

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

您可以在您的项目模型中尝试这样做:
def as_json(options={})super(include::user)end
Hi all。。。“我两个都试一下,然后回复。”Thanh为回复晚表示歉意。很抱歉这很有效。谢谢如果你愿意的话,你可以加上这个作为答案。
def as_json(options = {})
  super(include: :user)
end