Subclassing models in Rails

不羁的心 提交于 2019-12-04 04:29:50

Why don't you use modules?

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 is using Single Table Inhritance pattern by default (just google for it), so when you're subclassing a model, all the resulting models will use the same database table (in this case posts). You can put all your common methods and validations in the Post model, and specific ones in the other classes, but all those classes will have access to each other's fields, because they share the same table (that's not a big problem though).

If you just want to share code (methods), you'd be better off just putting some common methods into a module in a file in the lib directory and including it in each model. Or you could put the module definition at the top if you're keeping all the models in a single file like in your example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!