Rails: Pros and Cons of multiple models

179 views Asked by At

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).

2

There are 2 answers

0
Greg Burghardt On BEST ANSWER

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
2
The Whiz of Oz On

OK this is just one of many ways of doing it. I usually create a Profile model, which belongs to a User. One user can either have one Profile, or, if this app is going to grow and allow one User to manage multiple properties, it could have many Profiles later on. Inside these Profiles you can use PGSQL HStore (tutorial here) to store many small preferences (tel1, tel2, address, address_work, etc.) to keep your database from cluttering. Good luck!