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格式的所有關聯嗎?
你可以試試這個,在你的項目模型:'高清as_json(選項= {})超(包括:用戶端) ' – Thanh
大家好...虐待嘗試兩個然後迴應。 – Sylar
@Thanh遲到的迴應道歉。抱歉。這很好。謝謝!如果你願意,你可以添加這個答案作爲答案。 – Sylar