0

I have a ton of models (>50) and each share a same set associations.

Like so.

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

Since the relation is exactly same for all my models (we need to keep track which user changed a record), anyway to to include these associations with one call?

Something like this? (this doesn't work)

Basically I would like something like:

class Foo < ActiveRecord::Base
  include DefaultUserAssociation
  # other associations
end
Roger
  • 7,121
  • 5
  • 35
  • 61

1 Answers1

5

Move it to a concern

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

and include it in the required models

class Foo < ActiveRecord::Base
  include DefaultUserAssociation
end
webster
  • 3,489
  • 3
  • 32
  • 55
  • 2
    Awesome, exactly what I needed! New that that concerns folder would come in handy some day ... :-) – Roger Jan 18 '18 at 11:32