Wow, got myself lost as soon as I left the hand-holding exercises in
the books.
I’m trying to set it up so when I click the (scaffold-generated)
‘destroy’ link on one (of a list) of parent MySQL records, the children
records in a different table get deleted also.
Very simple setup: my tables are ‘customers’ and ‘accounts’
class Customer < ActiveRecord::Base
has_many :accounts, :order => “cmp_code”
end
class Account < ActiveRecord::Base
belongs_to :customer
end
I used migrate to create the tables.
The table ‘accounts’ has a field called customer_id (int).
It was easy to add a “add new account to this customer” form to the
show.rhtml for my ‘list’ view. That works great. And I can destroy a
customer record just fine (using the auto-generated destroy link). But I
can’t figure out how to also destroy the accounts that are associated
with a customer via customer_id.
I have a
class ListController < ApplicationController
that lists all the customers, no problem.
That ListController class has the default destroy method that deletes
the selected customer from the database, simply:
Customer.find(params[:id]).destroy
My questions:
-
Should a MySQL foreign key have been created (either automatically or
by me) in the database? Because MySql Admin does not show any foreign
keys. -
Should a destroy on the parent in ‘customers’ destroy the children in
‘accounts’ due to the dynamically-created has_many and belongs_to
relationships? (It doesn’t, hence this post) I thought that was one of
the purposes of the has_many and belongs_to ? -
Assuming the answer to (2) is ‘no’ and I have to do that
destroy-children records manually, what code would I add to the destroy
method so the accounts are deleted where accounts[customer_id] = the id
for the record whose ‘destroy’ link is clicked? I’m sure it;s simple,
but I tried several things with no luck.
Thanks!