Saving objects and :id revisited
Posted on September 25, 2006 - Filed Under Ruby
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.
Popularity: 3% [?]
Hits for this post: 2692
Similar Posts
- First save, then use :id
- Migrations with advanced data operations
- foobar not loaded yet – in Rails console
- Pagination, AJAX and GROUP BY
- RNS – edit routes
Comments
Leave a Reply


