我正在创建一个项目,但每当我尝试create grade
Class student
使用current_user.grade.create()
或current_user.create_grade()
获取错误时“未定义的方法为nil类创建”
我的代码如下。
Student.rb
class Student < User
has_one :user_grade , dependent: :destroy, foreign_key: 'user_id'
has_one :grade , through: :user_grade
end
Grade.rb
class Grade < ApplicationRecord
has_many :user_grades, dependent: :destroy
has_many :admins, through: :user_grades
has_many :teachers, through: :user_grades
has_many :students , through: :user_grades
has_many :guardians, through: :user_grades
has_many :posts, dependent: :destroy
validates_presence_of :cls
end
user_grade.rb
class UserGrade < ApplicationRecord
belongs_to :grade
belongs_to :admin, optional: true, class_name: 'Admin', foreign_key: 'user_id'
belongs_to :teacher, optional: true, class_name: 'Teacher', foreign_key: 'user_id'
belongs_to :student, optional: true, class_name: 'Student', foreign_key: 'user_id'
belongs_to :guardian, optional: true, class_name: 'Guardian', foreign_key: 'user_id'
end
答案 0 :(得分:1)
尝试使用current_user.grade = Grade.new({})
。然后调用current_user.save
将保存关联并保存新的Grade
。