gpt4 book ai didi

ruby-on-rails - 如何在 Rails 中使用模型关注点

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:04 28 4
gpt4 key购买 nike

我正在尝试将模型的不同部分转移到关注点中。其中两个是 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

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

最佳答案

你需要这样定义它。

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 文件夹用于放置在更多模型 之间共享的代码。您应该放置实现某些行为的 modules,而不是从您的模型中提取代码并将其放入 concerns

CodeClimate 阅读这篇文章

引自此链接。

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

关于ruby-on-rails - 如何在 Rails 中使用模型关注点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31021194/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com