Я реализую класс Student, который наследуется от класса User, используя STI в Rails.Каждый Студент связан с StudentRecord через has_one , где каждый StudentRecord принадлежит Студенту.
В консоли , когда я добавляюStudentRecord через student.build_student_record
, и я звоню student.save
Я получаю ошибку в форме "ActiveRecord :: StatementInvalid ..." .Однако, когда я тестирую эту же функциональность, используя rails test
, я не получаю ошибок ...
test / models / student_test.rb:
class StudentTest < ActiveSupport::TestCase
test "create Student with student_record" do
student = Student.create(
name: "Example Student",
email: "example@student.org",
password: "foobar",
password_confirmation: "foobar")
student.build_student_record(student_number: 12345)
student.save
student = student.reload
assert_equal 12345, student.student_record.student_number
end
end
Вот фотография ошибка консоли , и я добавил свой другой соответствующий код ниже.
app / models / user.rb:
class User < ApplicationRecord
...
end
db / migrate / [timestamp] _add_type_to_users:
class AddTypeToUsers < ActiveRecord::Migration[5.1]
def change
add_column :users, :type, :string
end
end
app / models / student.rb:
class Student < User
has_one :student_record
end
db / migrate / [timestamp] _create_student_records.rb:
class CreateStudentRecords < ActiveRecord::Migration[5.1]
def change
create_table :student_records do |t|
t.integer :student_number
t.references :student, foreign_key: true
t.timestamps
end
end
end
app / models / student_record:
class StudentRecord < ApplicationRecord
belongs_to :student
validates :student_id, presence: true
validates :student_number, presence: true
end