ruby继承。将一个对象转换为另一个对象
我不知道我要做什么的术语,所以谷歌搜索已经证明是非常困难的 我有两个ruby类ruby继承。将一个对象转换为另一个对象,ruby,Ruby,我不知道我要做什么的术语,所以谷歌搜索已经证明是非常困难的 我有两个ruby类 class A < ActiveRecord::Base end class B < A end class A
class A < ActiveRecord::Base
end
class B < A
end
class A
类是命中数据库的对象。类a中有一列存储预期的类名。在本例中,A类中该列的值为“b”
我的愿望是找到一种方法来调用a,并实际得到B。我的想法是,未来不仅仅会有B,我可能会得到C、D甚至E。所有这些类都可能需要独特的方法。Rails的单表继承可以帮助您:这被称为STI(单表继承)。实现它的正确方法是将名为
type
的列添加到基类表中。Rails将使用此列了解要为给定记录实例化的类。
例如,假设我们有三个班,Person
,Teacher
和Student
Person
是基类,Teacher
和Student
继承自基类。在这种情况下,我们按如下方式实施:
迁移:
class CreatePeople < ActiveRecord::Migration
def change
create_table :people do |t|
... # person attributes name, birthday ...
... # Student specific attributes
... # Teacher specific attributes
t.string :type # this will be Student, Teacher or Even Person.
t.timestamps null: false
end
end
end
然后通过Person
课程
person = Person.first
puts person.type # => Student
创建新学生时,请确保其属性设置正确,例如,学生没有设置教师的特定属性。您只需在控制器中通过强参数过滤它们(假设这是一个Rails应用程序)在纯Ruby中实现这一点的另一种方法是从调用a的方法返回B
class A < ActiveRecord::Base
def b
return B.new(self)
end
end
class B
def initialize(a)
@a = a
end
# if you need to get methods belonging to A
def method_missing(*args, &block)
@a.send(*args, &block)
end
end
class A
Rails比单表继承有更多的ou和更少的ou。在这里看到更多:谢谢,这看起来像我要找的。
person = Person.first
puts person.type # => Student
class A < ActiveRecord::Base
def b
return B.new(self)
end
end
class B
def initialize(a)
@a = a
end
# if you need to get methods belonging to A
def method_missing(*args, &block)
@a.send(*args, &block)
end
end