遍历rails文档并遇到了针对ActiveRecord模型的creating callback classes的建议。尽管在描述它们的用法方面做得很好,但并未列出确切的位置。这样做最合适的目录是什么?
答案 0 :(得分:2)
我建议在app/models/callbacks/
中创建一个文件夹,并按如下所示组织文件:
- app
- models
- callbacks
user.rb
user.rb
然后:
class User < ApplicationRecord
after_create ::Callbacks::User
after_destroy ::Callbacks::User
# we have to prepend :: here because it would try to refer to the namespace
# ActiveModel::Validations::Callbacks otherwise
end
&
module Callbacks
module User
# Warning: If you want to refer to the User model in there, you will have to
# prepend it with `::` so it looks up from the root because this module has
# the same name as the User model
# ex:
# ::User::SOME_CONSTANT
# and not
# User::SOME_CONSTANT
def self.after_create(user)
::Services::Emails::Welcome.enqueue!(user_id: user.id)
end
def self.after_destroy(user)
::Services::Emails::Goodbye.enqueue!(user_id: user.id)
end
# ...
end
end
这也是使用服务对象的简单结构。