Hello all and thank you for reading this message.
I am new to RoR, and ruby too, but i am quite excited about it.
I am developing a RoR project and with active record associations in
the following
manner
Tables (all tables have only one record)
CREATE TABLE webcars_development
.cars
(
id
int(11) NOT NULL auto_increment,
model_id
int(11) NOT NULL default ‘0’,
photo
blob,
created_at
datetime default NULL,
updated_at
datetime default NULL,
PRIMARY KEY (id
),
KEY FK_CARS_MODELS
(model_id
),
CONSTRAINT FK_CARS_MODELS
FOREIGN KEY (model_id
) REFERENCES
models
(id
)
);
CREATE TABLE webcars_development
.models
(
id
int(11) NOT NULL auto_increment,
name
varchar(64) NOT NULL default ‘’,
brand_id
int(11) NOT NULL default ‘0’,
created_at
datetime default NULL,
updated_at
datetime default NULL,
PRIMARY KEY (id
),
UNIQUE KEY name_idx
(nome
),
KEY FK_MODELS_BRAND
(brand_id
),
CONSTRAINT FK_MODELS_BRAND
FOREIGN KEY (brand_id
) REFERENCES
brands
(id
)
);
CREATE TABLE webcars_development
.brands
(
id
int(11) NOT NULL auto_increment,
name
varchar(16) NOT NULL default ‘’,
created_at
datetime default NULL,
updated_at
datetime default NULL,
PRIMARY KEY (id
),
UNIQUE KEY name_idx
(name
)
);
Models
class Car < ActiveRecord::Base
belongs_to :model
has_one :brand, :through => :models
validates_presence_of :model_id
end
class Model < ActiveRecord::Base
belongs_to :brand
has_one :car, :through => :models
validates_associated :brand
validates_presence_of :brand, :message => ‘is unknown’
end
class Marca < ActiveRecord::Base
has_one :model, :through => :brands
end
Controller (only index action needed for the example)
class CarsController < ApplicationController
def index
@cars = Cars.find(:all)
end
end
The view
Brand | Model | Photo |
---|---|---|
<%=h car.model.brand.name %> | <%=h car.model.name %> | <%=h car.photo %> |