RoR - how can I refer to 'old' self object when self's context changes inside a method
My rails app has Podcast and Track models. Podcasts have many Tracks, Tracks belong to Podcasts.
Here's the boring background info:
We upload our audio files to mixcloud. For each show they host, they provide a json representation in addition the standard html version. Our app gets and parses this json feed and uses the returned data to set attributes on the Podcast object being created.
We can also use the feed to get the names of all Tracks belonging to this Podcast, and then create those Tracks in our database while we are creating the Podcast.
The code more or less works, but it fails to set :podcast_id on any of the new tracks:
before_validation :create_tracks
def create_tracks
# get json feed for podcast which is hosted hosted on mixcloud.com
json = a_method_that_gets_and_parses_json(self.json_url)
json.sections.each do |section|
if sect开发者_运维百科ion.section_type=="track"
# track.name IS being set, but podcast_id is NOT being set, it is always null
Track.create(:name=>section.track.name, :podcast_id=>self.id)
end
end
end
I realise that the problem is being caused by the fact that the context of self changes when we use it inside the Track.create method. It no longer refers the Podcast as it does when we return self.json_url
outside the .each
loop.
So if I can't use self here, how can I pass the id of the current podcast to the Track.create method? I've tried setting variables outside and inside the method but nothing seems to work here. For the record, the tracks are being created, their names are being set correctly, just the podcast_id that I can't seem to set.
The context of self
is not going to be changing here. It will still be the same Podcast
object that you have.
The problem is that you are calling this method before_validation
which happens before the object is saved and therefore before the object is given an id. You probably want to call this after_create
rather than before_validation
, as that's when the object's ID will have been assigned.
精彩评论