Rails所有模型的基本关联?

Rails basic associations for all models?

我有大量模型 (>50),每个模型共享一个 相同 集关联。

像这样。

class Foo < ActiveRecord::Base
    belongs_to :created_by_user, foreign_key: :created_by, class_name: 'User'
    belongs_to :updated_by_user, foreign_key: :updated_by, class_name: 'User'
    belongs_to :deleted_by_user, foreign_key: :deleted_by, class_name: 'User'
    # other associations
end

由于我的所有模型的关系完全相同(我们需要跟踪哪个用户更改了记录),无论如何要在一个调用中包含这些关联?

是这样的吗? (这不起作用)

基本上我想要这样的东西:

class Foo < ActiveRecord::Base
  include DefaultUserAssociation
  # other associations
end

将其移至问题

app/models/concerns/default_user_association.rb

module DefaultUserAssociation
  extend ActiveSupport::Concern

  included do
    belongs_to :created_by_user, foreign_key: :created_by, class_name: 'User'
    belongs_to :updated_by_user, foreign_key: :updated_by, class_name: 'User'
    belongs_to :deleted_by_user, foreign_key: :deleted_by, class_name: 'User'
  end
end

并将其包含在所需的模型中

class Foo < ActiveRecord::Base
  include DefaultUserAssociation
end