Postgresql / Rails 3 / Ruby 1.9.2 / OSX
class Deliverable < ActiveRecord::Base
has_many :models, :dependent => :destroy
def build_template
models << sect_letterhead << sect_ica << sect_project_description_exhibit
end
end
ruby-1.9.2-p180 :002 > d.models.first
=> #<Model id: 1, company_id: nil, deliverable_id: 1, model_id: nil, type: nil, kind: "cover_page", csv_file_name: nil, csv_content_type: nil, csv_file_size: nil, csv_updated_at: nil>
ruby-1.9.2-p180 :003 > d.models.first.update_attribute(:csv_file_name, "blah")
=> true
ruby-1.9.2-p180 :004 > d.models.first
=> #<Model id: 5, company_id: nil, deliverable_id: 1, model_id: nil, type: nil, kind: "opening_letter", csv_file_name: nil, csv_content_type: nil, csv_file_size: nil, csv_updated_at: nil>
Whenever I update_attribute a model, that model is pushed to the end of the array. Is there any way other than assigning a custom sort attribute to avoid changing the array order when update_attribute is called? I could fairly easily do this, but I am interested in the behavior of the database.
Even when I remove the timestamps from the model object, the behavior remains.
How does this occur if there are no timestamps to keep track of which model was just updated? Or is the model actually pulled out of the array and put back in the last position when I call update_attribute?
I’m no PostgreSQL expert, but I’ve noticed the same behaviour. My understanding is that PostgreSQL doesn’t have a default order, per se (whereas MySQL is reliable – as far as I know – in ordering by the primary key). PostgreSQL’s data format maybe means that modified records are shifted to the end.
In short: this isn’t a Rails thing – it’s a PostgreSQL thing, hence why timestamps don’t matter.
Either way, it forces you to be clear about the order you want items returned in. Not a terrible idea.