如何创建我们自己的基类并从基类而不是ActiveRecord :: Base继承所有模型

时间:2014-03-11 08:46:00

标签: ruby-on-rails activerecord

我正在研究一个项目,在该项目中,每个模型我们有两个共同的属性

  1. Created_ts
  2. CREATED_BY
  3. 我想添加一个基类,我想在其中设置这些属性,我尝试使用

    class BaseModel < ActiveRecords::Base
    
    end
    
    class Person < BaseModel
    
    end
    

    当我创建Person模型的实例时,它会给出异常,我不确定它为什么会给出异常,可能是因为它正在寻找表BaseModels。

    任何人都可以建议,如何做到这一点。

    例外:

    PG::UndefinedTable: ERROR:  relation "base_models" does not exist
    LINE 5:                WHERE a.attrelid = '"base_models"'::regclass
                                              ^
    :               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                         pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
                    FROM pg_attribute a LEFT JOIN pg_attrdef d
                      ON a.attrelid = d.adrelid AND a.attnum = d.adnum
                   WHERE a.attrelid = '"base_models"'::regclass
                     AND a.attnum > 0 AND NOT a.attisdropped
                   ORDER BY a.attnum
    
    ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "base_models" does not exist
    LINE 5:                WHERE a.attrelid = '"base_models"'::regclass
                                              ^
    :               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                         pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
                    FROM pg_attribute a LEFT JOIN pg_attrdef d
                      ON a.attrelid = d.adrelid AND a.attnum = d.adnum
                   WHERE a.attrelid = '"base_models"'::regclass
                     AND a.attnum > 0 AND NOT a.attisdropped
                   ORDER BY a.attnum
    

1 个答案:

答案 0 :(得分:0)

我们只需要将基类作为抽象类

更多参考资料寻求以下链接

Rails extending ActiveRecord::Base