私は、DeviseでUser
モデルを作成し、type
カラムなどを追加しました。したがってモデルStudent
とTeacher
はそれを継承する可能性があります。このすべてがうまくいった。私のTeacher
モデルは、モデルCourse
と1対多の関係にあり、教師コースに関するすべてのデータが保存されています。Railsシングルテーブル継承ヘルパーを作成する
私の問題:courses
テーブルに列がないため、Devitsヘルパーcurrent_user.courses
が機能しませんuser_id
。コースの属性がteacher_id
であっても、current_user
は.courses
を解決できるようにするにはどうすればよいですか?
私はRailsの初心者ですから、どんな助けもありがとうございます! :)
EDIT:洗練された質問と追加されたスキーマとモデル。
# 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
あなたは 'schema.rb'を追加することができますし、 /またはモデル? –