Ruby on rails ActiveRecord::RecordInvalid:验证失败:用户必须存在
我正在处理单表继承的问题。我有两种不同类型的用户。用户模型和培训师模型,培训师用户应从用户模型继承属性。我在rails控制台中创建了一个用户,一切正常。当我试图创建一个培训师时,我得到了以下错误。 Rails 5.0.4Ruby on rails ActiveRecord::RecordInvalid:验证失败:用户必须存在,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我正在处理单表继承的问题。我有两种不同类型的用户。用户模型和培训师模型,培训师用户应从用户模型继承属性。我在rails控制台中创建了一个用户,一切正常。当我试图创建一个培训师时,我得到了以下错误。 Rails 5.0.4 ActiveRecord::RecordInvalid: Validation failed: User must exist 我是否错误地设置了模型关联 这是我的用户模型 class User < ApplicationRecord # Include defau
ActiveRecord::RecordInvalid: Validation failed: User must exist
我是否错误地设置了模型关联
这是我的用户模型
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
从我的用户模型中可以看到,我添加了required:type列
这是我的客户和约会的模式
create_table "appointments", force: :cascade do |t|
t.integer "client_id"
t.integer "trainer_id"
t.datetime "appointment_date"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "start_time"
t.datetime "end_time"
t.integer "status", default: 0
end
create_table "clients", force: :cascade do |t|
t.string "name"
t.string "phone_number"
t.integer "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
首先,我在控制台中创建了一个用户
User.create!(email:'ryan@test.com', password:'asdfasdf', password_confirmation:'asdfasdf')
然后,我开始创建培训师
Trainer.create!(first_name:'Ryan', last_name:'Bent')
培训师和用户应该有关联。但是我认为我不需要使用单表继承添加关联。对于单表继承,一个表必须具有任何子类所需的所有属性()。因此,对于您的情况,您需要将培训师列(名字、姓氏)也添加到
users
表中,然后用户将该列留空在表中,培训师将填写它们
如果要保留单独的表,您所做的不再是单个表,需要在2个表之间进行某种连接。是否与
培训师
和用户
关联?他们之间有什么联系吗?还提供约会
和客户端
的结构。请提供更多的代码(客户端和约会模式)以及您在控制台中尝试运行的内容。希望使用“加密密码”实际上,您指的不是加密,而是密码散列,例如PBKDF2
或BCrypt
@zaph,这正是designe库所称的列,是的,它使用BCrypt
User.create!(email:'ryan@test.com', password:'asdfasdf', password_confirmation:'asdfasdf')
Trainer.create!(first_name:'Ryan', last_name:'Bent')