簡體   English   中英

跨父應用程序和引擎的模型關聯

[英]Model association that spans across parent app and engine

我正在制作一個在控制器中引用current_user的Rails引擎,如下所示:

require_dependency "lesson_notes/application_controller"

module LessonNotes
  class NotesController < ApplicationController

    def index
      if current_user
        @notes = Note.where(student: current_user) if current_user.user_type.name == "student"
        @notes = Note.where(teacher: current_user) if current_user.user_type.name == "teacher"
      end
    end

  end
end

這是非常冗長的,似乎我可以做這樣的事情:

require_dependency "lesson_notes/application_controller"

module LessonNotes
  class NotesController < ApplicationController

    def index
      @notes = current_user.notes if current_user
    end

  end
end

但是, 用戶模型存在於父應用程序中,而不存在於engine中

Note模型中,我可以用它來定義belongs_to關聯:

module LessonNotes
  class Note < ActiveRecord::Base
    belongs_to :student, class_name: "::User"
    belongs_to :teacher, class_name: "::User"
  end
end

如何在User模型中定義關聯的另一端has_many

這就是我最終這樣做的方式...

在父應用中:

class User < ActiveRecord::Base

  has_many   :notes, class_name: LessonNotes::Engine::Note, foreign_key: "teacher_id"

end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM