简体   繁体   English

Rails删除联接表中的记录

[英]Rails deleting record in join table

I have two associated tables, 'releases' & 'tracks' which contain the fields 'name' and 'isrc' respectively. 我有两个关联的表,“ releases”和“ tracks”,分别包含字段“ name”和“ isrc”。

I am trying to remove all tracks from the database when release.name is equal to a certain value, eg "Thriller". 我试图在release.name等于某个值(例如“ Thriller”)时从数据库中删除所有轨道。

The relationship here is that 'track' belongs_to a 'release' and a 'release' has_many 'tracks'. 这里的关系是“ track”属于“ release”和“ release” has_many“ tracks”。

Can anyone help me with how to achieve this within the Rails console? 谁能在Rails控制台中帮助我实现这一目标?

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 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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