Search code examples
ruby-on-railsdatabasepostgresqldatabase-designhstore

Rails Database Design with Similar models with different attributes


I am designing an application that has many types of "requests" the requests are to be handled in a very similar nature to one another but they contain different data.

They each have about 1/3 of the information the same, dates, user information etc.

However different types of requests have completely different information, and a request can have about 30 columns in the database.

ie.

Form A
Date Submitted
User
Email
Provider
Attribute A
Attribute B
Attribute C
Attribute D

then

Form A
Date Submitted
User
Email
Provider
Attribute E
Attribute F
Attribute G
Attribute H

I will have about 40 models in the end, so don't want to have separate tables.

What is the best way to represent this, I need full control over the layout of the show and forms.

I have previously accomplished this using HStore (with postgres) and was wondering if there were any other suggestions.

[EDIT]

Examples of same attributes accross models:

:company_name,:contact_person,:physical_address,:contact_email,:contact_phone

Example of Form A:

:mobile_current_provider,:num_mobile_connections,:num_smartphones,:operating_system,:num_high_voice_users

Example of Form B

:kw_per_month, :weekend_power, :three_phase_power, :seasonal_difference

Most of the fields are either strings or integers (with a few booleans), but can all be coerced into a string. Most of the data is simply used to be displayed, other than the fields in common which will be used for searches and calculations etc


Solution

  • After reading the added examples of attributes, my impression is they are better off to belong to other models.

    My proposal is to create two more ActiveRecord models: MobileUsage and ElectricityUsage

    class User < ActiveRecords::Base
      has_one :mobile_usage
      has_one :electricity_usage
    end
    
    class MobileUsage < ActiveRecords::Base
      belongs_to :user
    end
    
    class Electricity < ActiveRecords::Base
      belongs_to :user
    end
    

    The benefits:

    • Better organization. Mobile belongs to mobile usage, and eletricity belongs to electricity usage
    • No null data in User. If you put all of the attributes in one model User, some users many have mobile info without electricity, and vice versa. This will leave lots of null data in table.

    Then, for Form A, you can just load the attributes of mobile usage in a nested form. The attributes for user will be saved to user and mobile info will be saved to mobile with a reference. Form B is the similar.

    With the separation, you can even allow user to fill basic info at first, then details later.