我正在寻找实现此类/数据关系的方法。
我具有以下数据表示形式:
Parent类有一个孩子列表。
每个子类确实具有一些数据(例如created_at,updated_at和其他数据)以及可以访问的一个“数据类”(男孩,女孩,外星人或我想在其后添加的任何其他类...)
可以假定男孩,女孩,外星人和其他来自孩子的阶级具有非常不同的数据。
这应该是一个简单的继承案例,但是事实证明要找到合适的例子非常困难。我一直在阅读一些有关STI(您有多种类型的数据相似的项目,因此不适合使用)和MTI(您有一种数据类型可以由不同类型使用的信息,例如帖子可以组和个人,例如Facebook类型),但是我找不到一个简单的案例来表示这种类型的数据组织。
到目前为止,我有一个Child,其中包含一个id + type来指向特定数据(男孩/女孩/外星人),但是我基本上必须自己使用Constantize来管理一切。
是否有更好的方式处理继承?
class parent < ActiveRecord::Base
has_many :children
end
class child < ActiveRecord::Base
belong_to :parent
# has_one (???) -> use gettypeclass instead
def gettypeclass
# switch type, then constantize type and find instance id
end
end
class boy < ActiveRecord::Base
belong_to :child
def process()
# do something special
end
end
class girl < ActiveRecord::Base
belong_to :child
def process()
# do something special
end
end
class alien < ActiveRecord::Base
belong_to :child
def process()
# do something special
end
end
# now I can do something like
parent.children.first.gettypeclass.process()
有关此数据的一些事情:
create_table :parent do |t|
t.timestamps
end
create_table :child do |t|
t.integer :parent_id
t.integer :data_id
t.integer :data_type
# some data
t.timestamps
end
create_table :boy do |t|
t.integer :child_id
# some data
end
create_table :girl do |t|
t.integer :child_id
# some data
end
create_table :alien do |t|
t.integer :child_id
# some data
end