[英]How to set has_many association between parent app's model and mounted engine's model?
[英]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.