Topic: How to maintain order of child records when saving nested model?
I am using Rails' nifty accepts_nested_attributes_for feature for creating invoices and their respective items. Items can be added dynamically to an invoice with jQuery.
class Invoice < ActiveRecord::Base attr_accessible :project_id, :number, :date, :recipient, :items_attributes accepts_nested_attributes_for :items end
This works fine. Except for the order in which Rails saves the items.
For example when I create an invoice with these 5 items...
A B C D E
... everything works fine. But when I then hit Create to save the invoice plus items to the database, the order is completely randomised, for example like this:
D A C E B
A peek into my database and the created_at column of my items table revealed that Rails (or SQLite?) seemingly saves the items in a random order and not in the order in which I (as a user) added them to the invoice.
Is this normal behaviour and if so how can I maintain a proper ordering on the items that I add to my invoice?
Thanks for any help...