简体   繁体   中英

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, eg "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?

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.

it should work:

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

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM