Destroy data from 2 different tables

I'm trying to delete an account but at the same time i'd like to delete the portals that belongs to the account. This is what i wrote but it's not working. how can i deal with this problem?

I have this code inside the account controller in the "destroy" method def destroy   @account = Account.find(params[:id])   @portal = Portal.find(:all, :conditions => ['account_id = ?', @account.id ])   @portal.destroy   @account.destroy end any ideas?

the error displays this:

NoMethodError in AccountsController#destroy

undefined method `destroy' for #<Array:0x47982a0> app/controllers/accounts_controller.rb:78:in `destroy' Request

Parameters:

{"_method"=>"delete", "authenticity_token"=>"f8c32ed76159e1b51b0883ef72a4ab801b92d322", "id"=>"11"}

I'm guessing the error is coming on line:

@portal.destroy

Right? The reason why is that:

@portal = Portal.find(:all, :conditions => ['account_id = ?', @account.id ])

returns an array, even if there is only one result. Check this out:

User.find(:all, :conditions => "id = 1").class

=> Array

Only one result is returned but it is wrapped in an array. And class Array does not have a destroy method, hence the error. One simple way around this would be to do:

@portals = Portal.find(:all, :conditions => ['account_id = ?', @account.id ]) ... @portals.each { |p| p.destroy }

HTH,

Matt

or @portals = Portal.find(:first, :conditions ['account_id = ?', @account.id]) #which will return a single AR instance

which would be a problem if Account has_many :accounts

J

And by :accounts I think Jodi means :portals :slight_smile:

RoR_Nb wrote:

I'm trying to delete an account but at the same time i'd like to delete the portals that belongs to the account. This is what i wrote but it's not working. how can i deal with this problem?

Why not specify it in the models?

class Portal < ActiveRecord::Base   belongs_to :account end

class Account < ActiveRecord::Base   has_many :portals, :dependent => :destroy end

delete the Account, and the Portals go poof!

RoR_Nb wrote:

-- I also tried this :

solution #2       class Portal < ActiveRecord::Base         belongs_to :account       end

      class Account < ActiveRecord::Base         has_many :portals, :dependent => :destroy       end but it only deleted the account record,

Curious...

does your Portal model include an account_id?

I use the :dependent => :destroy, and can cascade deletes down several levels of models...

Use :dependent=>:destroy only if you need to do some 'clean up' processing in the child models. Destroy instantiates each of the models before deleting them. If you don't need to do any processing then use the more db-efficient :dependent=:delete_all