按对应表的属性删除连接表记录

时间:2012-11-18 19:28:47

标签: ruby-on-rails activerecord join

我有用户:

has_many :user_artists
has_many :artists, :through => :user_artists

UserArtist:

belongs_to :artist
belongs_to :user
delegate :itunes_id, :to => :artist

艺术家

has_many :user_artists
has_many :users, :through => :user_artists
attr_accessible :itunes_id

我想基于该艺术家的给定itunes_id销毁给定用户的user_artists。我可以做User.first.user_artists.select {|ua| ua.itunes_id == 200823564}但是有没有办法只使用ActiveRecord?或者这是最有效的方式吗?

我在想User.first.user_artists.where( :artist => {:itunes_id => 1000}).destroy_all之类的东西,但SQL抱怨user_artists上没有artist.itunes_id列。

1 个答案:

答案 0 :(得分:1)

怎么样

User.first.user_artists.join(:artist).where('artist.itunes_id = ?', 1000).destroy_all