Reputation: 948
I have a nested resources:
resources :bills do
resources :debts
end
and when I make a delete link in the index html in the debts view like this:
<td>
<%= link_to "Delete", [@bill, @debt], confirm: "Are you sure?", method: :delete %>
</td>
the bill is deleted, not the debt. What happens?, How can I deleted only one debt of a specific Bill? This is my delete action in my debt's controller.
def destroy
@bill = Bill.find(params[:bill_id])
@debt = @bill.debts.find(params[:id])
@debt.destroy
flash[:notice] = "The debt was successfully deleted"
redirect_to bill_debts_url
end
And my models:
Bill model:
class Bill < ActiveRecord::Base
has_many :debts
end
Debt model:
class Debt < ActiveRecord::Base
belongs_to :bill
end
Thanks in advance!
Upvotes: 0
Views: 439
Reputation: 26997
You have a has_many
association. If a bill
has_many
debts
, then bill.debts
is an association, not a single object. You need to call destroy_all
on that object to destroy all of them:
def destroy
@bill = Bill.find(params[:bill_id])
@debts = @bill.debts.find(params[:id])
@debts.destroy_all
flash[:notice] = "The debt was successfully deleted"
redirect_to bill_debts_url
end
That being said, I'm not sure why the Bill
is being destroyed at all...
Upvotes: 1