Rails trigger AASM event on nested associations autosave

264 Views Asked by At

I have a parent and child model schema defined with each having its own AASM state machine

class Project < ApplicationRecord
  has_many :tasks, autosave: true
  include AASM

  aasm do
    state :created, initial: true
    state :in_progress
    state :completed

    event :start do
      transitions from: :created, to: :in_progress
    end
 end
end
class Task < ApplicationRecord
  belongs_to :project

  include AASM

  aasm do
    state :open, initial: true
    state :in_progress
    state :failed
    state :reopened
    state :closed, after: :notify_task_closed

    event :close do
      transitions from: :in_progress, to: :closed
    end
  end
end

Now I have a page where users can edit the project and also edit/perform-aasm-actions in bulk on the tasks. Now when a user submits such request, I receive the edited fields and the actions(events) to be triggered on tasks.

Since autosave is enabled for the tasks association for the Project class, I would like to perform a single save to

  • Update project attributes
  • Update task attributes
  • Trigger respective events on the tasks.

The catch is to run validations for each of the above points and revert the whole transaction in case any step fails.

I am stuck on the following questions

  1. What would be the right pattern to achieve this during autosave?
  2. When and how to trigger AASM events during autosave?
  3. How to bubble up errors if there are any validations/guard failures?
0

There are 0 best solutions below