cyrilchampier
cyrilchampier

Reputation: 2248

Rails: save a model associations in a single transaction

I have troubles with updated_at columns, that does not seems to be equal inside the same transaction:

@my_model = FactoryGirl.build(:my_model_bare)
@my_model.first_assoc = FactoryGirl.build(:first_assoc_sample)
@my_model.second_assoc = FactoryGirl.build(:second_assoc_sample)
@my_model.save!
puts @my_model.first_assoc.updated_at.iso8601(3)
puts @my_model.second_assoc.updated_at.iso8601(3)

At the end, first_assoc.updated_at != second_assoc.updated_at even if both models have been saved inside the same transaction !?

How can I force updated_at to be the same for all operation inside a transaction ? Is it a mysql problem ?

Upvotes: 0

Views: 378

Answers (2)

dmcnally
dmcnally

Reputation: 771

The 'created_at' and 'updated_at' columns are populated by Rails.

As you are using FactoryGirl I'm assuming you need this for testing purposes. Based on that take a look at the TimeCop gem:

https://github.com/travisjeffery/timecop

Timecop gives the ability to freeze time.

If you really need to set the created_at and updated_at times manually you can just assign them values:

current_time = Time.now

@my_model.created_at = current_time
@my_model.updated_at = current_time

You would need to manually set the values for any related objects too

Upvotes: 1

user3099088
user3099088

Reputation: 1

ActiveRecord sets updated_at in datetime with ms. So they will not be equal. For see it you can use:

Rails.logger.info @model.updated_at.to_i

You always can update update_at manually.

Upvotes: 0

Related Questions