Mario Zigglesworth
2011-Aug-12 18:45 UTC
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! -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
John Hinnegan
2011-Aug-13 06:08 UTC
Re: Getting nil value when setting an on Join model via a has_many :through relationship
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 http://guides.rubyonrails.org/association_basics.html#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 -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-talk/-/810FHkvTw30J. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.