I am implementing a Student class which inherits from a User class using STI in Rails. Each Student is associated with a StudentRecord via a has_one association where each StudentRecord belongs to a Student.
In the console , when I add a StudentRecord via student.build_student_record
and I call student.save
I receive an error of the form "ActiveRecord::StatementInvalid..." . However, when I test this same functionality using rails test
I receive no errors...
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
Here is a photo of the console error , and I have added my other relevant code below.
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
KBIIX's solution above appears to fix the error too, however I have ended up changing the line in db/migrate/[timestamp]_create_student_records.rb to:
t.references :student, foreign_key: { to_table: :users }
..in case anyone is curious.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.