在Rails中对模型进行子类化 [英] Subclassing models in Rails

查看:95
本文介绍了在Rails中对模型进行子类化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two models, Article and Recipe, which have a bunch of the same attributes and methods. I want to make the subclasses of a new class "Post" and move all their shared logic in there so I'm not maintaining duplicate code. I've tried this:

class Recipe < Post; end
class Article < Post; end
class Post < ActiveRecord::Base
     #all the shared logic
end

所有这些类均在标准./app/models文件夹中.但是,例如,当我转到/articles/new时,此代码将引发ActiveRecord :: StatementInvalid错误.错误是:

All of these classes are in the standard ./app/models folder. This code, however, throws a ActiveRecord::StatementInvalid error when I go to /articles/new, for instance. The error is:

找不到表格帖子"

Could not find table 'posts'

有什么想法要设置吗?

推荐答案

为什么不使用模块?

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"

这篇关于在Rails中对模型进行子类化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆