在Rails中对子模型进行子类化

weo*_*tch 7 model ruby-on-rails subclassing

我有两个模型,Article和Recipe,它们有一堆相同的属性和方法.我想创建一个新类"Post"的子类,并在那里移动所有共享逻辑,所以我不维护重复的代码.我试过这个:

class Recipe < Post; end
class Article < Post; end
class Post < ActiveRecord::Base
     #all the shared logic
end
Run Code Online (Sandbox Code Playgroud)

所有这些类都在标准的./app/models文件夹中.但是,当我转到/ articles/new时,此代码会抛出ActiveRecord :: StatementInvalid错误.错误是:

找不到表'帖子'

知道如何设置吗?

Mat*_*att 13

Rails默认使用Single Table Inhritance模式(只是google for it),因此当您对模型进行子类化时,所有生成的模型将使用相同的数据库表(在本例中posts).您可以将所有常用方法和验证放在Post模型中,将特定的方法和验证放在其他类中,但所有这些类都可以访问彼此的字段,因为它们共享同一个表(尽管这不是一个大问题).

如果您只想共享代码(方法),最好只将一些常用方法放入lib目录中文件的模块中,并将其包含在每个模型中.或者,如果您将所有模型保存在单个文件中,则可以将模块定义放在顶部.


Sim*_*tti 9

你为什么不用模块?

module Features
  def hello
    p "hello"
  end
end

class Recipe < ActiveRecord::Base
  include Features
end

class Article < ActiveRecord::Base
  include Features
end


Recipe.new.hello
# => "hello"

Article.new.hello
# => "hello"
Run Code Online (Sandbox Code Playgroud)