1

我试图将模型的不同部分移入关注点。其中两个是 AASM 定义的状态,以及 Paperclip 的附件。

所以,我将相关代码移动到单独的文件中。

应用程序/模型/关注/user_aasm.rb

class User
    module UserAasm
        extend ActiveSupport::Concern
        included do
            include AASM
            aasm do
            state :unverified, initial: true
            state :approved
            state :suspended
            state :deleted
            state :banned
          end
        end
    end
end

在我的 user.rb 中,我做

include UserAasm

我收到以下错误:

Unable to autoload constant UserAasm, expected app/models/concerns/user_aasm.rb to define it

我想知道我在代码中出了什么问题。如何以正确的方式使用它?

4

2 回答 2

3

你需要像这样定义它。

require 'active_support/concern'

module UserAasm
    extend ActiveSupport::Concern
    included do
        include AASM
        aasm do
        state :unverified, initial: true
        state :approved
        state :suspended
        state :deleted
        state :banned
      end
    end
end

然后在你的User模型中

include UserAasm

这不是让您的模型变瘦的正确方法,因为concerns文件夹用于放置在多个models. 您应该将modules其实现一些行为,而不是从模型中提取代码并将其放入concerns

从CodeClimate阅读这篇文章

从此链接引用。

'使用这样的 mixin 类似于通过将杂物倒入六个独立的垃圾抽屉并砰地关上来“清理”一个凌乱的房间。当然,它表面上看起来更干净,但垃圾抽屉实际上使识别和实现澄清域模型所需的分解和提取变得更加困难。

于 2015-06-24T08:18:08.693 回答
1

模块需要在类之外定义。

所以里面app/models/concerns/user_aasm.rb

module UserAasm
  extend ActiveSupport::Concern
  included do
    include AASM
    aasm do
    state :unverified, initial: true
    state :approved
    state :suspended
    state :deleted
    state :banned
    end
  end
end
于 2015-06-24T08:16:32.687 回答