我用 Devise 创建了一个User
模型,并添加了type
列等,因此Student
和Teacher
的模型可以从中继承。所有这些都很好用。我的Teacher
模型与模型Course
具有一对多关系,其中存储了有关教师课程的所有数据。
我的问题:设计助手current_user.courses
不起作用,因为courses
表没有列user_id
。如何使current_user
能够解析.courses
,即使课程中的属性称为teacher_id
?
我是 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
您可以通过以下方式定义自己的帮助程序:
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
我没有执行这些语法,但我过去写过这样的东西,所以如果你遇到任何语法错误,请把它发布在评论中。
编辑:
看到您更新的模型代码后,我认为将用户模型中的course
关联更改为如下所示将对您有用:
has_many :courses, :foreign_key => "teacher_id"
运行:
rails generate migration AddUserReferenceToCourses user:references
我认为这将创建一个迁移,为课程增加user_id
您可以向课程表添加迁移:
rails g migration add_user_id_to_courses user:references
这将在 course.rb 文件中添加belongs_to :user
。然后转到 user.rb 文件并添加:
has_many :courses
此关系将允许您从课程或从用户调用课程。