Ruby on rails 创建正确的继承
我在RubyonRails中创建类之间的正确继承时遇到问题 想法: 有两类:个人和客户。Person是一个抽象类,客户端继承Person属性 问题: 我的解决方案不起作用。我不知道为什么。如何正确实现(首选CTI)继承 迁移: 创建_persons.rbRuby on rails 创建正确的继承,ruby-on-rails,ruby,inheritance,Ruby On Rails,Ruby,Inheritance,我在RubyonRails中创建类之间的正确继承时遇到问题 想法: 有两类:个人和客户。Person是一个抽象类,客户端继承Person属性 问题: 我的解决方案不起作用。我不知道为什么。如何正确实现(首选CTI)继承 迁移: 创建_persons.rb class CreatePersons < ActiveRecord::Migration def self.up create_table :persons do |t| t.string :pesel, nul
class CreatePersons < ActiveRecord::Migration
def self.up
create_table :persons do |t|
t.string :pesel, null: false
t.string :first_name, null: false
t.string :last_name, null: false
t.string :email, null: false
t.date :data_of_birth, null: false
t.string :password_digest, null: false
# required for STI
t.string :type
t.timestamps null: false
end
end
def self.down
drop_table :persons
end
end
class CreatePersons
创建_clients.rb
class CreateClients < ActiveRecord::Migration
def change
create_table :clients do |t|
add_foreign_key :persons
t.timestamps null: false
end
end
end
class CreateClients
模范人物
class Person < ActiveRecord::Base
self.abstract_class = true
end
class-Person
模型客户端
class Client < Person
end
class客户端
在db:migrate之后,当我尝试Client.create(pesel:“1232”,…)时,出现错误:
客户端的未知属性“pesel”
单表继承基于使用一个表来存储所有记录。
您的问题是,您创建了一个表“clients”,Rails默认情况下将其用于Client类
只需rake db:回滚上一次迁移,它就应该查找超类表“people”,并且工作正常
编辑:Oops,没有看到您提到CTI,此解决方案仅适用于STI。您遇到了一个错误,因为除了您的
人员
表之外,您还创建了一个客户
表。如果每个类都有一个单独的表,那么唯一继承的就是代码,而不是数据库的内容
(STI)允许您添加类型
列,然后父类和子类的实例将存储在单个表中,前提是子类的预期表不存在。您已经添加了type
列,但还创建了clients
表。这意味着ActiveRecord希望您在该表中存储客户端
实例,而不是人员
——并且当它尝试在那里存储客户端
时,它无法使用导致错误的pesel
字段
因此,如果要使用STI,则需要删除客户
表,并向人员
表中添加特定于客户的字段
或者,您可以保留客户
表,并将人员
中您也希望用于客户的字段添加到客户
表中。这将不是STI,但您的客户机
对象将从个人
继承方法
从您包含的
类型
字段中,我怀疑您想摆脱客户机
表。看看这里:您是否已经考虑过使用合成路线而不是继承路线?