[Rails] Re: Re: Child record becomes orphan
Jake Janovetz
jakejanovetz at yahoo.com
Sun Jan 1 22:46:34 GMT 2006
Gerard wrote:
> def destroy_company
> if Company.find(params[:id]).contacts
Here, you're just grabbing "contacts" from the Company class.
> flash[:notice] = 'This company has contacts.'
>
> ## With this line it works
> @company = Company.find(params[:id])
This is the first time you initialize the "@company" instance.
> redirect_to :action => 'show_company', :id => @company.id
> else
> Company.find(params[:id]).destroy
> redirect_to :action => 'list_companies'
> end
> end
I'm still a bit hung-over from last night, so forgive if I'm not
answering the question correctly. :)
Your method is similar to how I delete things, too. Check to see if
there are objects under that company and notify the user. If the user
confirms, I delete the company and dependent objects. (I don't require
the user to delete all contacts first, though)
In your code above, you called Company.find(params[:id]) twice because
you never stored the instance. You could have done:
@company = Company.find(params[:id])
if company.contacts.size > 0
flash[:notice] = 'This company has contacts.'
redirect_to :action => 'show_company', :id => @company.id
else
@company.destroy
redirect_to :action => 'list_companies'
end
I don't recall right now, but I think you have to test
company.contacts.size. Your test above just checks "if
company.contacts" which I think will always evaluate true even if there
are no contacts.
Jake
--
Posted via http://www.ruby-forum.com/.
More information about the Rails
mailing list