2012-05-23 24 views
1

我在使用STI的应用程序中有两个模型:Entry和Sugar,它们非常简单。为什么Rails生成器不会为特定模型创建属性和方法?

条目:

# == Schema Information 
# 
# Table name: entries 
# 
# id   :integer   not null, primary key 
# created_at :datetime  not null 
# updated_at :datetime  not null 
# user_id :integer 
# type  :string(255) 
# 

class Entry < ActiveRecord::Base 
    # attr_accessible :title, :body 
    belongs_to :user 
end 

糖业(注意,从注释宝石架构信息缺乏amount):

# == Schema Information 
# 
# Table name: entries 
# 
# id   :integer   not null, primary key 
# created_at :datetime  not null 
# updated_at :datetime  not null 
# user_id :integer 
# type  :string(255) 
# 

class Sugar < Entry 
    attr_accessible :amount 
end 

我通过运行rails g model Sugar amount:integer创建的糖模型,然后将其编辑成是Entry模型的子类。迁移创建生成量柱:

class CreateSugars < ActiveRecord::Migration 
    def change 
    create_table :sugars do |t| 
     t.integer :amount 

     t.timestamps 
    end 
    end 
end 

和列在我的数据库中存在:

bridges_development=# \d sugars 
            Table "public.sugars" 
    Column |   Type    |      Modifiers      
------------+-----------------------------+----------------------------------------------------- 
id   | integer      | not null default nextval('sugars_id_seq'::regclass) 
amount  | integer      | 
created_at | timestamp without time zone | not null 
updated_at | timestamp without time zone | not null 
Indexes: 
    "sugars_pkey" PRIMARY KEY, btree (id) 

然而,“量”的属性和/或方法似乎并不存在。以下是一个示例:

1.9.2-p290 :002 > s.amount = 2 
NoMethodError: undefined method `amount=' for #<Sugar:0xb84041c> (...) 

1.9.2-p290 :003 > s = Sugar.new(:amount => 2) 
ActiveRecord::UnknownAttributeError: unknown attribute: amount (...) 

为什么amount属性和关联的方法不可用?

+0

重新启动服务器? – apneadiving

+0

不是STI应该是N个模型 - 1个表? Sugar正在访问表格条目,其中没有属性数量。 – tokland

+0

托克兰 - 我认为你是对的...我知道这个问题将是一个疏忽,只要我发布它。 – cmhobbs

回答

0

STI的想法是N模型 - 1表。 Sugar实际上正在访问表entries,其中没有属性amount

1

当你做出从入门糖项继承那些可以由导轨使用STI(单表继承)

在这个方案中的所有类都存储在基类的表(项)和类型列存储的名称子类。因为他们都共享同一个表,他们也有着相同的属性:糖表将不会在所有

使用如果你不希望这样做,你也可以制作进入一个抽象类

class Entry < ActiveRecord::Base 
    self.abstract_class = true 
end 

在这种情况下,将不会有条目表,但会有一个糖表(对Entry的每个其他子类都有一个表)。

另一种方法是将Entry和Sugar应该共享的代码放入模块中。

相关问题