我正在实现一个学生类,该类从Rails中的STI继承自User类。每个学生通过 has_one 关联与StudentRecord相关联,其中每个StudentRecord 属于属于一个学生。
在控制台中,当我通过student.build_student_record
添加StudentRecord并调用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
这里是https://dotnetfiddle.net/30Y0M6,我在下面添加了其他相关代码。
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
答案 0 :(得分:1)
KBIIX的上述解决方案似乎也可以修复该错误,但是我最终将 db / migrate / [timestamp] _create_student_records.rb 中的行更改为:
DataFrame
..以防万一有人好奇。