First save, then use :id

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 ;-))

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.