开发者

Subclassing models in Rails

开发者 https://www.devze.com 2023-02-07 22:10 出处:网络
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

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开发者_如何学C < 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?


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.


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"
0

精彩评论

暂无评论...
验证码 换一张
取 消