edhamilton812
edhamilton812

Reputation: 15

Rails deleting record in join table

I have two associated tables, 'releases' & 'tracks' which contain the fields 'name' and 'isrc' respectively.

I am trying to remove all tracks from the database when release.name is equal to a certain value, e.g "Thriller".

The relationship here is that 'track' belongs_to a 'release' and a 'release' has_many 'tracks'.

Can anyone help me with how to achieve this within the Rails console?

Upvotes: 1

Views: 752

Answers (2)

Rails Guy
Rails Guy

Reputation: 3866

it should work:

Track.delete_all("release_id in ?", Release.select("id").where(name: 'Thriller'))

Thanks

Upvotes: 0

yarakyo
yarakyo

Reputation: 499

In your release model:

has_many :tracks, dependent: :destroy

This will remove all the tracks associated with a release from the database when you destroy a release.

You can test this by doing something like this in the console

release = Realse.where(name:"Thriller").first
release_id = release.id
release.destroy
tracks = Track.where(release_id:release_id)

The variable tracks should now be empty.

Upvotes: 1

Related Questions