4

我有一个使用单表继承的纸牌游戏应用程序。我有一个, 和一个带有 columnclass Card的数据库表,以及一些子类(包括and ,为了论证)。cardstypeCardclass Foo < Cardclass Bar < Card

碰巧的是,Foo是游戏原始印刷中的Bar牌,而是扩展包中的牌。为了使我的模型合理化,我创建了一个目录结构,如下所示:

app/
+ models/
  + card.rb
  + base_game/
    + foo.rb
  + expansion/
    + bar.rb

并修改 environment.rb 以包含:

Rails::Initializer.run do |config|
  config.load_paths += Dir["#{RAILS_ROOT}/app/models/**"]
end

但是,当我的应用从数据库中读取卡片时,Rails 会抛出以下异常:

ActiveRecord::SubclassNotFound (The single-table inheritance mechanism failed to locate the subclass: 'Foo'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Please rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Card.inheritance_column to use another column for that information.)

是否有可能完成这项工作,或者我注定要使用平面目录结构?

4

1 回答 1

3

可能最好的方法是将Foo类嵌套在BaseGame模块中。

ruby 模块与其他语言中的包结构大致相似,它是将相关代码位划分为逻辑组的机制。它具有其他功能,例如 mixins(您可以在此处找到解释:http ://www.rubyfleebie.com/an-introduction-to-modules-part-1/ ),但在这种情况下它们不相关。

您需要稍微不同地引用和实例化该类。例如,您会像这样查询它:

BaseGame::Foo.find(:all,:conditons => :here)

或者像这样创建它的一个实例:

BaseGame::Foo.new(:height => 1)

Rails 支持 Active Record 模型的模块化代码。您只需要对类的存储位置进行一些更改。例如,您将类 Foo 移动到模块 BaseGame 中(如您的示例中所示),您需要移动apps/models/foo.rbapps/models/base_game/foo.rb. 所以您的文件树将如下所示:

app/
 + models/
  + card.rb #The superclass
   + base_game/
      + foo.rb

要在类定义上声明它,如下所示:

module BaseGame
  class Foo < Card
  end
end
于 2010-05-26T12:59:50.317 回答