Rails:一种为相对大量的模型添加相同"belongs_to"语句的 DRY 方法



我有一个 rails 应用程序,其中包含许多模型,所有这些模型都有一个user_id字段,并且需要属于User模型,因为我想查看哪个用户使用 ActiveAdmin 创作了哪个记录以进行授权。

无论如何,我正在尝试找到一种 DRY 方法将此belongs_to :user语句添加到所有模型中。我尝试创建一个关注模块(?BelongsToUser但无法使其工作。我也研究过模型继承(STI(,但我认为它不适合我的情况。

这是我BelongsToUser关注的问题:

module BelongsToUser 
extend ActiveSupport::Concern
belongs_to :user
end

以下是我将其包含在模型中的方法:

class ModelName < ApplicationRecord
# Other Stuff
include BelongsToUser
# Other stuff
end

我收到以下错误:

未定义的方法"belongs_to",用于属于用户:模块

该模块的简单版本是这样的:

module BelongsToUser
extend ActiveSupport::Concern
included do 
belongs_to :user
end
end
class ModelName < ApplicationRecord
include BelongsToUSer
end

当然,这只有在您正在做比belongs_to :user更复杂的事情时才有意义,否则您只是在移动语句而不是干练逻辑,例如,如果您需要大量样板来创建关联。

另一种方法是添加一个类方法("宏"(到ApplicationRecord

class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.user_owned
belongs_to :user
end
end
class ModelName < ApplicationRecord
user_owned
end

不过,同样的警告也适用。

最新更新