lulalala
lulalala

Reputation: 17981

Is Rails created_at populated by Ruby or SQL?

How does Rails assign the created_at? It can theoretically be done at the Ruby layer or at the SQL layer.

I am asking this because I am hoping it is done at SQL layer. This helps determining some race conditions among several records. If it is from SQL layer, I can trust that the stamps represent when it actually ends up in the database available for others to see.

Upvotes: 1

Views: 243

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51171

It's done in ActiveRecord Timestamp module, here:

https://github.com/rails/rails/blob/master/activerecord/lib/active_record/timestamp.rb:

def _create_record
  if self.record_timestamps
    current_time = current_time_from_proper_timezone

    all_timestamp_attributes.each do |column|
      column = column.to_s
      if has_attribute?(column) && !attribute_present?(column)
        write_attribute(column, current_time)
      end
    end
  end

  super
end

def _update_record(*args, touch: true, **options)
  if touch && should_record_timestamps?
    current_time = current_time_from_proper_timezone

    timestamp_attributes_for_update_in_model.each do |column|
      column = column.to_s
      next if attribute_changed?(column)
      write_attribute(column, current_time)
    end
  end
  super(*args)
end

Upvotes: 3

Related Questions