Subclassing models in Rails

拜拜、爱过 提交于 2019-12-13 12:05:47

问题


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

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'

Any idea how to set this up?


回答1:


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"



回答2:


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.



来源:https://stackoverflow.com/questions/4852632/subclassing-models-in-rails

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