Trigger events on multiple records in gent_machine gem
I am using state_machine to transition states in one of my models. The transition successfully occurs on separate records. But what if I need to trigger an event on multiple records. I can make a transition in multiple posts with
@records.each &:event
But this method executes the request as many times as it exists @records
. How can I get the event to do a state transition with just one request. Please, help.
Thank.
source to share
In Rails (4), this can be accomplished with B#transaction
(or B#save
) as described in the SO section : keep an active array of records .
I have checked the results of a simple state_machine event on 200 entries and the results are noted below.
Instead:
@records.each &:event
# Completed 302 Found in 1700ms (ActiveRecord: 778.6ms)
do:
ActiveRecord::Base.transaction do
@records.each &:event
end
# Completed 302 Found in 977ms (ActiveRecord: 73.4ms)
As noted in the previous SO answer, this will wrap these transactions as one atomic activity.
Note . Likely error handling errors, which are not the case.
source to share