Chris
Chris

Reputation: 12181

Removing join-table record by attribute of opposite table

I have User:

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

UserArtist:

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

Artist

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

I want to destroy a given user's user_artists based on a given itunes_id for that artist. I can do User.first.user_artists.select {|ua| ua.itunes_id == 200823564} but is there a way to do it just using ActiveRecord? Or is this the most efficient way?

I was thinking something like User.first.user_artists.where( :artist => {:itunes_id => 1000}).destroy_all but SQL complains that there isn't a artist.itunes_id column on user_artists.

Upvotes: 0

Views: 49

Answers (1)

mkk
mkk

Reputation: 7693

How about

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

Upvotes: 1

Related Questions