How does an around_action callback work? An explanation is needed

后端 未结 2 998
北海茫月
北海茫月 2021-02-05 05:28

I am terribly confused about an around_action. How do they work? Can someone please provide me with an example/explanation of how they work?

This is a quote from my Agil

相关标签:
2条回答
  • 2021-02-05 05:36

    My understanding is as below:

    begin
        # Do before action...
        logger.info 'I am the before action'
    
        # Do the action, which is passed as a block to your "around filter"
        # Note that if you were to delete this line, the action will never be called!
        yield
    
        # Do after action...
        logger.info 'I am the after action'
    ensure
        raise ActiveRecord::Rollback
    end
    
    0 讨论(0)
  • 2021-02-05 05:56

    The key of the around_callback is yield. In the case of the wrap_in_transaction example: yield is replaced with the show action. When show ends (rendering inclusive), wrap_in_transaction continues and performs the rollback.

    At rails guides you can find:

    For example, in a website where changes have an approval workflow an administrator could be able to preview them easily, just apply them within a transaction: ... Note that an around filter wraps also rendering. In particular, if in the example above the view itself reads from the database via a scope or whatever, it will do so within the transaction and thus present the data to preview."

    That means the user at show can see the information before the rollback (in this case show must be doing a sort-of update which need a rollback because it is an information action).

    You can think that an around_callback is a before callback and an after callback in only one method, using yield to put the action in the middle.

    0 讨论(0)
提交回复
热议问题