2017-06-04 88 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