我的应用程序中有两个使用 STI 的模型:Entry 和 Sugar,它们非常简单。
参赛作品:
# == 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
我通过运行创建了 Sugar 模型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
属性和相关方法?