Saving objects and :id revisited

After I have discovered proper order object saving I read a little Rails documentation and… When Your app model have has_many and belongs_to (in my case Route has_many :points and Point belongs_to :rotue) Rails extends Your objects and in particular for Point adds property route which can be assigned with Route object. Like that:

pt.route = rt
pt.save
rt.save

And this will work despite when saving Point, Route still does not have valid ID in database. Why? Because Rails framework saving Route object will remember to update point in DB to write proper route_id. Rails will keep even backlog of created objects so following code will work as expect:

rt = Route.new
1.upto(5) {
  pt = Point.new
  pt.route = rt
  pt.save
}
rt.save

At the end all created Points will have route_id pointing to DB entry created with rt.save.

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.