I'm making a Rails engine that makes reference to the current_user
in a controller like so:
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 .
In the Note
model I have this to define the belongs_to
association:
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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.