Riley Grigg
Riley Grigg

Reputation: 21

How do I delete an item in rails?

I am doing a Ruby on Rails course and I am on a part where I am trying to delete a portfolio item but it is giving me an error. Here's the error.


ActiveRecord::InvalidForeignKey in PortfoliosController#destroy


PG::ForeignKeyViolation: ERROR: update or delete on table "portfolios" violates foreign key constraint "fk_rails_cc5ab4a1c3" on table "technologies" DETAIL: Key (id)=(12) is still referenced from table "technologies". : DELETE FROM "portfolios" WHERE "portfolios"."id" = $1


Extracted source (around line #52):


50
51 # Destroy/delete the record
52 @portfolio_item.destroy
53
54 # Redirect
55 respond_to do |format|`

Rails.root: /home/ubuntu/workspace/DevcampPortfolio/ClonedRepo/Devcamp-Portfolio


Application Trace | Framework Trace | Full Trace app/controllers/portfolios_controller.rb:52:in 'destroy'


Request

Parameters:

{"_method"=>"delete", "authenticity_token"=>"3fGuZqFrTblpS7aQGpfszjN24lSxu6SAr5/JRlLc0RDupDZ7BJKJr6kPnEYHa0/BR7rmTPnN+/i5Ptjb3wCLtw==", "id"=>"12"}


Response

Headers:

None


the code for the place I am in the course

my code


What do I change to fix it?

Upvotes: 0

Views: 188

Answers (1)

m3characters
m3characters

Reputation: 2290

You need to add dependent: :destroy to your has_many relation on the portfolio model.

has_many :technologies, dependent: :destroy This will make it so that when you destroy a portfolio it destroys the technologies that "belong" to the portfolio.

If you want to keep the technologies you need to change the relationship between them, or allow them to be parentless and hook a before_destroy action to the portfolio model.

Upvotes: 1

Related Questions