I’m working on a simple CMS. The main data type are “listings” a listing
habtm (has_and_belongs_to_many) categories and subcategories.
Subcategories belong_to categories. Subcategories are basically the same
as categories, but they are treated differently in a few situations.
The problem is, I can’t seem to write the view/controller/model code
that allows me to create a listing that contains subcategories! Even
though I’m using the exact same code I used for categories, the models
are the same, and the database configs are the same, the MySQL database
is never updated.
This is the form that’s used:
<% for category in @categories %>
@listing.categories = Category.find(params[:category_ids] # this
works
@listing.subcategories = Subcategory.find(params[:subcategory_ids] #
doesn’t
if @listing.save
…
…
end
And the databases:
create table listings (
id int not null auto_increment,
primary key (id)
);
create table subcategories (
id int not null auto_increment
name varchar(100) not null,
category_id int not null,
constraint fk_items_category foreign key (category_id) references
categories(id),
primary key (id)
);
create table listings_subcategories
(practically a duplicate of categories_listings, which works)
subcategory_id int not null,
listing_id int not null,
constraint fk_cp_subcategory foreign key (subcategory_id) references
subcategories(id),
constraint fk_cp_listing foreign key (listing_id) references
listings(id),
primary key (subcategory_id, listing_id)
);
When I try to create a listing with subcategories the array
subcategory_ids is populated correctly, and the listing is created, but
the listing has no subcategories and the table listings_subcategories
has no entries.
This problem has been driving me crazy all day. I’ve tried everything I
can think of to get it to work. If anyone has a clue, I will be greatly
indebted.
-Adam