undefined 方法 'create' for nil:nilClass



我正在创建一个项目,但每当我尝试使用current_user.grade.create()current_user.create_grade()create gradeClass student时都会收到错误"未定义的方法为 nil 类创建">

我的代码如下。

学生.rb

class Student < User
has_one :user_grade , dependent: :destroy, foreign_key: 'user_id'
has_one :grade , through: :user_grade
end

等级.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

尝试使用current_user.grade = Grade.new({}).然后调用current_user.save将保存关联并保存新Grade

相关内容

最新更新