NetManiac

Witold Rugowski on web20 wave with Ruby on Rails

First save, then use :id

Posted on September 22, 2006 - Filed Under Ruby

Well. Sometimes not all obvious things are so obvious ;-))

When creating some ActiveRecord objects, remember first to save it before using its :id. Lets look at this code:

rt = Route.new
pt = Point.new
pt[:route_id] = rt[:id]
rt[:name] = "New one"
rt.save
pt.save

Will this work? It will depend on this what You expect from this code. If You want associate point with route via route_id field, it won’t work. It dead simple – :id is taken from database, and hard to get :id, before You save record (and create proper entry in database table). So You get nil as rt[:id].

In this code it is seen at first glance, but when is span across much more lines with more actions on Route… Well it can be not seen so easily ;-))

Popularity: 3% [?]

Hits for this post: 3226

Similar Posts

Comments

Leave a Reply