Newbie question about has_and_belongs_to_many and destroy...

Hi all.

I think this must be a newbie moment, I really hope someone can help me out! :slight_smile:

I have a has_and_belongs_to_many relationship set up, all of which is working except for destroy! When I try to delete a company record with "Company.delete(1)" I get an error (below) from rails.

I have a "Company" table, and a "Category" table, and a join table between the 2 called categories_companies.

My company model looks like this :-

class Company < ActiveRecord::Base   has_and_belongs_to_many :Category end

and my Category model :-

class Category < ActiveRecord::Base   has_and_belongs_to_many :Company   acts_as_tree :order => "name" end

And finally, the error from script/console :-

Company.destroy(1)

NoMethodError: undefined method `clear' for Category:Class         from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.5/lib/ active_record/base.rb:1238:in `method_missing'         from (eval):3:in `destroy_without_callbacks'         from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.5/lib/ active_record/callbacks.rb:321:in `destroy_without_transactions'         from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.5/lib/ active_record/transactions.rb:125:in `destroy'         from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.5/lib/ active_record/connection_adapters/abstract/database_statements.rb: 59:in `transaction'         from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.5/lib/ active_record/transactions.rb:95:in `transaction'         from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.5/lib/ active_record/transactions.rb:121:in `transaction'         from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.5/lib/ active_record/transactions.rb:125:in `destroy'         from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.5/lib/ active_record/base.rb:488:in `destroy'         from (irb):1

Thanks all!

Anyone?

Matt Roberts wrote:

Anyone?

On Jan 14, 9:04 pm, Matt Roberts <roberts.mattrobe...@gmail.com>

Does it work if you do

Company.find(1).destroy

I've not tested this, but i'm thinking that Company.delete(1) might be a class method, which might not make the callbacks work (it does seem to be saying something about callbacks in the errors). Whereas the above would be an instance method.

Bit of a guess but worth a try...?

Anyone?

Not sure that it matters but as a general rule you should write
habtm :categories not habtm :Category (and similarly hatbm :companies)

Fred