2017-05-13 11 views
0

Devits를 사용하여 User 모델을 만들고 type 열을 추가 했으므로 StudentTeacher 모델을 상속받을 수 있습니다. 이 모든 것이 훌륭하게 작동했습니다. 내 Teacher 모델은 모델 Course과 일대 다 관계가 있으며 교사 과정에 대한 모든 데이터가 저장됩니다.Rails 단일 테이블 상속 도움말 작성자

내 문제 : courses 테이블에 user_id 테이블이 없기 때문에 Devise 도우미 current_user.courses이 작동하지 않습니다. 코스의 속성이 teacher_id이라해도 current_user.courses을 해결할 수 있도록하려면 어떻게해야합니까?

저는 Rails 초보자입니다. 그래서 어떤 도움을 주시면 감사하겠습니다! :)

편집 : 세련된 질문과 스키마와 모델이 추가되었습니다.

# schema.rb: 
create_table "courses", force: :cascade do |t| 
    t.string "title" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.integer "teacher_id" 
    t.index ["teacher_id"], name: "index_courses_on_teacher_id" 
    end 

    create_table "users", force: :cascade do |t| 
    t.string "email",     default: "", null: false 
    t.string "encrypted_password",  default: "", null: false 
    t.string "reset_password_token" 
    t.datetime "reset_password_sent_at" 
    t.datetime "remember_created_at" 
    t.integer "sign_in_count",   default: 0, null: false 
    t.datetime "current_sign_in_at" 
    t.datetime "last_sign_in_at" 
    t.string "current_sign_in_ip" 
    t.string "last_sign_in_ip" 
    t.datetime "created_at",       null: false 
    t.datetime "updated_at",       null: false 
    t.string "name" 
    t.string "type" 
    t.integer "quiz_session_id" 
    t.index ["email"], name: "index_users_on_email", unique: true 
    t.index ["quiz_session_id"], name: "index_users_on_quiz_session_id" 
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true 
    end 

# /app/models/course.rb: 
class Course < ApplicationRecord 
    belongs_to :teacher 
    has_many :students 

    delegate :teachers, :students, to: :users 
end 

# /app/models/user.rb: 
class User < ApplicationRecord 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
    has_many :courses 

    # Which users subclass the User model 
    def self.types 
    %w(Teacher Student) 
    end 

    # Add scopes to the parent models for each child model 
    scope :teachers, -> { where(type: 'Teacher') } 
    scope :students, -> { where(type: 'Student') } 

end 

# /app/models/teacher.rb: 
class Teacher < User 
end 
+0

당신은 당신의'schema.rb'를 추가 할 수 있습니다 :

, 내가 당신을 위해 작동합니다 아래 좋아하는 사용자 모델의 course 연결을 변경하는 생각 업데이트 된 모델 코드를보고 후/또는 모델? –

답변

1

이 방법으로 자신의 헬퍼를 정의 할 수 있습니다 :

class ApplicationController < ActionController::Base 

    protect_from_forgery with: :exception 
    helper_method :current_teacher, :current_student, 
       :teacher_logged_in?, :student_logged_in? 

    private 

    def current_teacher 
     @current_teacher ||= current_user if user_signed_in? and current_user.class.name == "Teacher" 
    end 

    def current_student 
     @current_student ||= current_user if user_signed_in? and current_user.class.name == "Student" 
    end 

    def teacher_logged_in? 
     @teacher_logged_in ||= user_signed_in? and current_teacher 
    end 

    def student_logged_in? 
     @student_logged_in ||= user_signed_in? and current_student 
    end 
end 

나는이 구문을 실행하지 않은하지만 당신은 어떤 구문 오류에 직면하는 경우 다음 의견으로 게시, 그래서 나는 과거에 이런 식으로 뭔가를 작성했습니다.

편집 :

has_many :courses, :foreign_key => "teacher_id" 
+0

고마워, 실제로'current_teacher.courses'를 호출 할 수있게 해주지 만, 이전과 같은 오류를 준다 :'SQLite3 :: SQLException : 그런 열이 없다 : courses.user_id : SELECT "courses". * FROM "courses"WHERE "courses". "user_id"=?'. 나는 current_user.courses가'Teacher'뿐만 아니라'Student'를 위해 일하는 해결책을 원합니다! – megahra

+0

그것은 작동합니다! 다시 배웠습니다 : D Thank you! – megahra

+0

한 가지 더 질문 : 저는'current_user.courses'를 Student 또는 Teacher로 로그인 했더라도 상관 없습니다. 지금은'=> "teacher_id"'만 추가했기 때문에 교사용 모델에서만 작동해야합니다. student_id " '에서도 작동하도록 어떻게 변경해야합니까? @sajan – megahra

0

실행 :

rails g migration add_user_id_to_courses user:references 

:

rails generate migration AddUserReferenceToCourses user:references 

은 그 당신은 과정 테이블에 마이그레이션을 추가 할 수 있습니다

+0

오, 나는 분명히 미안합니다 : 사용자 (모델 학생)로부터 물려받은 다른 클래스가 코스와 다른 관계를 가지고 있기 때문에 교사와 코스 간의 관계가 의도적 인 것입니다. – megahra

0

과정에 user_id를 추가합니다 마이그레이션을 만들 것이라고 생각 course.rb 파일에 belongs_to :user이 추가됩니다. 그런 다음 user.rb 파일에 가서 추가

has_many :courses 

이 관계를 당신이 사용자로부터 과정에서 사용자 또는 과정을 호출 할 수 있습니다.