Getting nil value when setting an on Join model via a has_many :through relationship

Hi All,

I've been trying to figure out what's wrong here for a little over a day and figured i'd reach out to the ROR list.

A pastie explains the code a bit better than directly in email: http://pastie.org/private/mvu0zr1xm18bsk6nfbyama

Basically i have an Artist, and he has many Songs through a join model called Releases. An artist can be "featured" on a song... take for example most rap songs where there is more than 1 artist on the track.

My goal here is to be able to set an artist as the featured on a song when creating the song... something like this: Artist.first.featured_songs.create!(:title => "blah"). Rails allows me to do that with the current association setup (in the pastie above) BUT for some reason the release.featured attribute is always set to nil.

Anyway ideas?

Thank you!

First off, that’s a crazy datamodel. I would really try to pull that apart more if you can. Intuitively, there is a noun missing. This would probably make your current problem easier to solve.

That aside, were I trying to solve your problem at hand, I would probably try using association callbacks

maybe something like:

class Artist

has_many :featured_songs, :through => :releases, :after_add => :set_featured_flag

def set_featured_flag(featured_song)

haven’t done this before on a through relationship before, I think you’ll have to search for the release object

r = Release.where(:artist => self).where(:song => featured_song) #order by newest if they’re not unique?

r.featured = true

r.save

end

end