加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails中的子类化模型

发布时间:2020-12-17 04:31:34 所属栏目:百科 来源:网络整理
导读:我有两个模型,Article和Recipe,它们有一堆相同的属性和方法.我想创建一个新类“Post”的子类,并在那里移动所有共享逻辑,所以我不维护重复的代码.我试过这个: class Recipe Post; endclass Article Post; endclass Post ActiveRecord::Base #all the shared
我有两个模型,Article和Recipe,它们有一堆相同的属性和方法.我想创建一个新类“Post”的子类,并在那里移动所有共享逻辑,所以我不维护重复的代码.我试过这个:
class Recipe < Post; end
class Article < Post; end
class Post < ActiveRecord::Base
     #all the shared logic
end

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

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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读