Product - Accessories: Active Record model?

Hi,

I’ve got the following SQL tables:


create table products (
lock_version int default 0,
id serial,
title varchar(32) not null,
short_description text not null,
long_description text not null,
product_type_id int null,
vat_id int not null,
primary key (id),
foreign key (product_type_id) references product_types (id),
foreign key (vat_id) references vats (id)
);

create table accessories (
lock_version int default 0,
id serial,
product_id int not null,
accessory_product_id int not null,
primary key (id),
foreign key (product_id) references products (id),
foreign key (accessory_product_id) references products (id)
);


I’d like to design an Active Record model, so I can avoid having to use
the “Accessory” class.

For example, it would be nice being able to do things like:

ProductABC.accessories -> List of products used as
accessories
ProductABC.accessory_of -> List of products for which
ProductABC is an accessory
ProductABC.accessories << ProductXYZ -> Adds ProductXY to the list of
accessories of ProductABC

I have tried doing a few things with/without “has_and_belongs_to_many”,
but without full success…

Thanks for your help!

Philippe

If it is a M:M relationship you are looking for, you will also need a
join table ‘accessories_products’ that ONLY has accessory_id,
product_id, and the two foriegn key constraints. Then in the models set
products and accessories to ‘has_and_belongs_to_many.’ See p.239 in
‘Agile Development with Rails’ for more info. Good luck!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs