【问题标题】:How do I avoid duplication of code using AASM?如何避免使用 AASM 重复代码?
【发布时间】:2014-09-18 11:22:49
【问题描述】:

所以我的项目中有多个模型,其中许多模型具有激活和停用功能,我使用 AASM 进行管理

aasm column: 'status' do
  state :active, :initial => true
  state :inactive

  event :deactivate do
    transitions :from => :active, :to => :inactive
  end

  event :activate do
    transitions :from => :inactive, :to => :active
  end
end

我想避免重复这段代码,它有 4 种不同的模型,我可能不会再向它们添加任何状态。

提前致谢

【问题讨论】:

    标签: ruby-on-rails aasm


    【解决方案1】:

    您可以使用此部分创建模块并将其放入models/concerns/lib/ 文件夹(或其他地方,只需确保您已上传它):

      module ActivateDeactivateStatuses
        extend ActiveSupport::Concern
    
        included do
          aasm column: 'status' do
            state :active, :initial => true
            state :inactive
    
            event :deactivate do
              transitions :from => :active, :to => :inactive
            end
    
            event :activate do
              transitions :from => :inactive, :to => :active
            end
          end
        end
      end
    

    在你的模型中:

      include ActivateDeactivateStatuses
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-29
      • 1970-01-01
      • 2021-06-20
      • 2018-08-16
      • 2014-03-07
      相关资源
      最近更新 更多