2017-06-04 115 views
0

我需要使用清理我的代码中:包括模型协会从模型

# 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格式的所有关联吗?

+0

你可以试试这个,在你的项目模型:'高清as_json(选项= {})超(包括:用户端) ' – Thanh

+0

大家好...虐待尝试两个然后回应。 – Sylar

+0

@Thanh迟到的回应道歉。抱歉。这很好。谢谢!如果你愿意,你可以添加这个答案作为答案。 – Sylar

回答

0

在你的项目模型,覆盖as_json方法包括联想user

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