【问题标题】:Include model associations from within the model包括模型中的模型关联
【发布时间】: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


【解决方案1】:

在您的项目模型中,覆盖 as_json 方法以包含关联 user:

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

【讨论】:

    猜你喜欢
    • 2012-03-05
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多