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

时间:2014-04-23 06:56:08

标签: ruby-on-rails rails-engines

我正在创建一个Rails引擎,它引用控制器中的current_user,如下所示:

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

但是,用户模型存在于父应用中,而不是引擎

Note模型中,我有此定义belongs_to关联:

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

如何在has_many模型中定义关联的另一面 - User

1 个答案:

答案 0 :(得分:1)

这就是我最终做到的方式......

在父应用中:

class User < ActiveRecord::Base

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

end