I've got two models in my application using STI: Entry and Sugar, they're very simple.
Entries:
# == 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
Sugar (note the lack of amount
in the schema info from the annotate gem):
# == 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
I created the Sugar model by running rails g model Sugar amount:integer
and then edited it to be a subclass of the Entry model. The migration generated created an amount column:
class CreateSugars < ActiveRecord::Migration
def change
create_table :sugars do |t|
t.integer :amount
t.timestamps
end
end
end
And the column exists in my database:
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)
However, the "amount" attribute and/or methods don't seem to exist. Here's an example:
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 (...)
Why wouldn't the amount
attribute and associated methods be made available?
The idea of STI is N models - 1 table. Sugar
is in fact accessing table entries
, where there is no attribute amount
.