在模型中包含模型关联

时间:2017-06-04 07:44:16

标签: ruby-on-rails ruby-on-rails-5 rails-api

我需要清理我的代码:

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

1 个答案:

答案 0 :(得分:0)

在您的项目模型中,覆盖from PyQt5.QtWidgets import * class Widget1(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent=parent) lay = QVBoxLayout(self) for i in range(4): lay.addWidget(QPushButton("{}".format(i))) class Widget2(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent=parent) lay = QVBoxLayout(self) for i in range(4): lay.addWidget(QLineEdit("{}".format(i))) class Widget3(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent=parent) lay = QVBoxLayout(self) for i in range(4): lay.addWidget(QRadioButton("{}".format(i))) class stackedExample(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent=parent) lay = QVBoxLayout(self) self.Stack = QStackedWidget() self.Stack.addWidget(Widget1()) self.Stack.addWidget(Widget2()) self.Stack.addWidget(Widget3()) btnNext = QPushButton("Next") btnNext.clicked.connect(self.onNext) btnPrevious = QPushButton("Previous") btnPrevious.clicked.connect(self.onPrevious) btnLayout = QHBoxLayout() btnLayout.addWidget(btnPrevious) btnLayout.addWidget(btnNext) lay.addWidget(self.Stack) lay.addLayout(btnLayout) def onNext(self): self.Stack.setCurrentIndex((self.Stack.currentIndex()+1) % 3) def onPrevious(self): self.Stack.setCurrentIndex((self.Stack.currentIndex()-1) % 3) if __name__ == '__main__': import sys app = QApplication(sys.argv) w = stackedExample() w.show() sys.exit(app.exec_()) 方法以包含关联as_json

user