Search code examples
ruby-on-railsrubymodels

Rails: Pros and Cons of multiple models


I'm running a Rails 4 app and have a question about how to structure it. My application has users. These users have many fields that can be grouped into categories, such as Personal Info, Work Info, Home, etc.

My question deals with whether I should make separate models for each of these subgroups so users have many has_one associations, or instead just name the fields in the following fashion: personal_info_name, personal_info_address, work_info_address, etc.

Here are some of my thoughts for grouping into models:

Pros:

  • organization
  • readibility

Cons:

  • takes more database space
  • more models means more files/overhead

Is there a "Rails-way" to do this/what are some other pros/cons for having multiple models?

P.S.

I've read a bit about the "fat model, skinny controller" ideas, but am not sure I entirely understand them (if they pertain to the question).


Solution

  • You should still use proper has_one relations, but utilize ActiveRecord delegates to create shortcut methods:

    class User < ActiveRecord::Base
      has_one :personal_info, ...
      has_one :work_info, ...
      delegate :personal_info_name, to: 'personal_info.name'
      delegate :personal_info_address, to: 'personal_info.address'
      delegate :workd_info_address, to: 'work_info.address'
    end
    

    Of course, assuming you are using Active Record as an ORM. Otherwise, you could go the manual route:

    class User
      attr_accessor :personal_info, :work_info
    
      def personal_info_name
        personal_info.name unless personal_info.nil?
      end
    
      def personal_info_address
        personal_info.address unless personal_info.nil?
      end
    
      def work_info_address
        work_info.address unless work_info_address.nil?
      end
    end