1

我使用以下结构使用单表继承:

class Business < ActiveRecord::Base
end

class Restaurant < Business
end

class Bar < Business
end

并希望以字符串数组的形式获取子类列表,因此对于 Business -> ['Restaurant', 'Bar']

关于我将如何解决这个问题的任何想法?

4

3 回答 3

3

这是处理它的一种方法。

意见我个人喜欢这种方法,因为当子类从父类继承时,父类可以定义特定的行为或配置

class Business

  @@children = []

  def self.inherited(klass)
    @@children << klass
  end

  def self.children
    @@children
  end

end

class Restaurant < Business; end
class Bar < Business; end

让我们看看它的工作原理

Business.children
#=> [Restaurant, Bar]
于 2013-08-27T15:53:13.847 回答
2

你可以做:

Business.descendants.map {|klass| klass.name.demodulize } #generally I nest descendant in the main class namespace, hence the demodulize 

顺便说一句,由于 Rails 开发环境原则,您在开发时可能会遇到问题。

例如,如果您使用范围:Business.a_scope您可能会遇到问题。

Business在主类(此处)的底部添加 id 是已知且已知的方法,例如:

your_children_types.each do |type|
  require_dependency "#{Rails.root}/app/models/#{ path_to_your_child(type) }"
end
于 2013-08-27T15:53:06.237 回答
0

没有评论@naomik 答案的声誉,但如果您使用的是 Rails,请记住在添加到继承方法之后还要添加“超级”,例如:

def self.inherited(klass)
  @@children << klass
  super # this is 'super' important to not wipe out Rails' descendant tracker
end
于 2014-01-17T18:02:12.840 回答