简体   繁体   English

跨父应用程序和引擎的模型关联

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

I'm making a Rails engine that makes reference to the current_user in a controller like so: 我正在制作一个在控制器中引用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

This is quite verbose and it would seem I could do something like this instead: 这是非常冗长的,似乎我可以做这样的事情:

require_dependency "lesson_notes/application_controller"

module LessonNotes
  class NotesController < ApplicationController

    def index
      @notes = current_user.notes if current_user
    end

  end
end

However, the user model exists in the parent app, not the engine . 但是, 用户模型存在于父应用程序中,而不存在于engine中

In the Note model I have this to define the belongs_to association: Note模型中,我可以用它来定义belongs_to关联:

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

How would I define the other side of the association - the has_many - in the User model? 如何在User模型中定义关联的另一端has_many

This is how I ended up doing it... 这就是我最终这样做的方式...

In the parent app: 在父应用中:

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