Rails所有模型的基本关联?

Rog*_*ger 0 ruby-on-rails associations ruby-on-rails-5

我有很多模型(> 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
Run Code Online (Sandbox Code Playgroud)

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

像这样的东西?(这不起作用)

基本上我想要像:

class Foo < ActiveRecord::Base
  include DefaultUserAssociation
  # other associations
end
Run Code Online (Sandbox Code Playgroud)

web*_*ter 5

把它移到一个问题

应用程序/模型/关注/ 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
Run Code Online (Sandbox Code Playgroud)

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

class Foo < ActiveRecord::Base
  include DefaultUserAssociation
end
Run Code Online (Sandbox Code Playgroud)

  • 太棒了,正是我需要的!关于文件夹的新内容有一天会派上用场...... :-) (2认同)