如何在 rails 中使用模型关注点

How to use model concerns in rails

我正在尝试将模型的不同部分转移到关注点中。其中两个是 AASM 定义的状态,以及带有 Paperclip 的附件。

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

app/models/concerns/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

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

模块需要在class之外定义。

所以里面 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

你需要这样定义。

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

的这篇文章

引自此link。

'Using mixins like this is akin to “cleaning” a messy room by dumping the clutter into six separate junk drawers and slamming them shut. Sure, it looks cleaner at the surface, but the junk drawers actually make it harder to identify and implement the decompositions and extractions necessary to clarify the domain model.'