Clark Taylor
Clark Taylor

Reputation: 441

Splitting rails active record models

I like the idea of keeping models tight and creating new classes or modules for specific logic (keeping in line with the single-responsibility principle).

From what I understand Active Record associations, scopes and validations all belong to an active record model within rails. However, sometimes these alone can make a model file quit large. Would splitting an active record model into sub models using class_eval pass the coding sniff test? See example below:

# app/models/user.rb
class User < ApplicationRecord
  include Associations
  include Validations
  include Scopes
end

# app/models/user/associations.rb
class User
  module Associations
   User.class_eval do
     # insert belongs_to, has_many, etc.
   end
  end
end

# app/models/user/scopes.rb
class User
  module Scopes
   User.class_eval do
     # insert scopes
   end
  end
end

# app/models/user/validations.rb
class User
  module Validations
   User.class_eval do
     # insert validations
   end
  end
end

Upvotes: 1

Views: 132

Answers (0)

Related Questions