【发布时间】:2017-06-04 07:44:16
【问题描述】:
我需要清理我的代码使用:
# 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 格式显示所有关联吗?
【问题讨论】:
-
你可以在你的项目模型中试试这个:
def as_json(options = {}) super(include: :user) end -
大家好...我会尝试一下然后回复。
-
@Thanh 为迟到的回复道歉。对不起。那效果很好。谢谢!如果您愿意,可以将此添加为答案。
标签: ruby-on-rails ruby-on-rails-5 rails-api