Inconsistent before_create behavior

Hello.

1. When before_create returns false: a) active transaction is COMMITED if it was called from model.save b) active transaction is ROLLED BACK if it was called from model.save!

Is it intended ? If yes, how to dynamically determine if before_create semantics - ie. whether it commits or rollbacks on fail (as it depends on how it was called) ?

2. I create some models in before_create callback. In this process something my fail. Is it possible to ROLLBACK the transaction even if it was invoked by save ?

I tried:

a) wrapping operations on model in Model.transaction do ... end- does not work as transactions cannot be nested.

b) raise ActiveRecord::Rollback - works with save but when user calls save! exception isnt thrown on failure (as it is expected to be).

c) calling connection.rollback_db_transaction Seems to work but it is an ugly hack that has a side effect of generating: BEGIN, ..., ROLLBACK, COMMIT/ROLLBACK to the database that results in warnings.

d) What is correct way of doing it?

e) Maybe I should use different mechanism rather than before_create callback. Basically I need to attach a few other models to newly created model. If saving of any model fails, I want to leave database untouched and report failure to the user.

Regards.

e) Maybe I should use different mechanism rather than before_create callback. Basically I need to attach a few other models to newly created model. If saving of any model fails, I want to leave database untouched and report failure to the user.

How can you do this in before_create when the new model that you're attaching to doesn't exist yet? I would have though after_create makes more sense?

(sorry that doesn't answer your question)

Xav

e) Maybe I should use different mechanism rather than before_create callback. Basically I need to attach a few other models to newly created model. If saving of any model fails, I want to leave database untouched and report failure to the user.

How can you do this in before_create when the new model that you're attaching to doesn't exist yet? I would have though after_create makes more sense?

You can, to an extent. The associated objects get actually saved only when the main object is saved. However, I didn't get this to work correctly (at least in a fairly complex test setting) recently so I switched to after_save and everything started to behave correctly. An after_filter should work as well if everything is inside a transaction and you use save! for saving the associated objects as well.

//jarkko