Confusion with counter and single table inheritance


#1

I’m having trouble getting the magical counter to work in a rails app
with single table inheritance.

following is the relevant code.

thank you

class declarations

class Job < ActiveRecord::Base
has_many :vents
end

class Vent < ActiveRecord::Base
belongs_to :job, :counter_cache => true
validates_numericality_of :width
end

class Rectangular < Vent
validates_numericality_of :height
end

table declarations

CREATE TABLE jobs (
id int(10) unsigned NOT NULL auto_increment,
name char(40) NOT NULL default ‘’,
user_id int(11) NOT NULL default ‘0’,
vents_count int(11) default ‘0’,
created_at timestamp NOT NULL default CURRENT_TIMESTAMP on update
CURRENT_TIMESTAMP,
updated_at timestamp NOT NULL default ‘0000-00-00 00:00:00’,
total decimal(12,2) unsigned default ‘0.00’,
address_id int(11) NOT NULL default ‘0’,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE vents (
id int(10) unsigned NOT NULL auto_increment,
type char(20) NOT NULL default ‘’,
width int(10) unsigned default NULL,
height int(10) unsigned default NULL,
rise int(10) unsigned default NULL,
left tinyint(3) unsigned default NULL,
right tinyint(3) unsigned default NULL,
job_id int(10) unsigned default ‘0’,
created_at timestamp NOT NULL default CURRENT_TIMESTAMP on update
CURRENT_TIMESTAMP,
updated_at timestamp NOT NULL default ‘0000-00-00 00:00:00’,
price decimal(10,2) unsigned NOT NULL default ‘0.00’,
free_area_in float default NULL,
free_area_ft float default NULL,
active tinyint(3) unsigned default ‘1’,
flange_id int(10) unsigned NOT NULL default ‘0’,
order_id int(10) unsigned default NULL,
quantity int(10) unsigned NOT NULL default ‘1’,
square_feet float default ‘0’,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

controller code

def create
@job = Job.find(session[:job])
@type = @params[:vent][:type]
case @type
when “Rectangular”
@vent = Rectangular.new(@params[:vent])
end
if @vent.save
flash[:notice] = ‘Vent was successfully created.’
redirect_to(:controller => ‘/store’, :action => ‘show’, :id =>
session[:job])
else
render :action => ‘new’
end

   @job.vents << @vent
 end