Don Cheadle
Don Cheadle

Reputation: 5576

Rails Different types of Model have different number of and type of fields

In rails web app, user can "make" a Document. There are different types of documents :

  1. Loan
  2. Business
  3. Insurance

Each type of Document will have some things in common such as: account_num, doc_id, at least 1 name, but then they have different attributes.

For example:

Loan is only doc with a loan_type field

Business documents can have 1+ name attributes

If these docs may have different number of attributes, do they need to be completely separate models, or is there a way to incorporate a doc_type attribute for Document which then reveals what, and how many, attributes are associated with the Document? If so, what would that look like?

Upvotes: 1

Views: 797

Answers (2)

Maya Webster
Maya Webster

Reputation: 164

Depends on what you're going to need, but in general if your models have a strong commonality that part can all be in the same table, and include a type column that specifies the class name. This is called single table inheritance.

Any differences between the models give you some interesting options. If there are only a few differences, the columns could simply be included. If there are several, or the columns in question may be only sparsely populated, you can introduce a new table for the extra columns that belongs_to one of the models. For example, you could have an alternate_names table for businesses.

class AlternateNames < ActiveRecord::Base
  belongs_to :business
end

In the unlikely case that you don't need to search on the extra data, you can even keep it in the same table, with a column named something like extra_data, and serialize a hash of extra attributes. Each class can handle this data as appropriate.

class Document < ActiveRecord::Base
  # your code
  serializes :extra_data
end

class Business < Document
  def names
    [name] + extra_data[:names]
  end
end

Upvotes: 1

user229044
user229044

Reputation: 239311

What you're describing is the express purpose of single-table inheritance in Rails.

Use one table with a super-set of all the fields from all the models. Add a type column, and then create your three models, inheriting from a base model, and you're pretty much done.

Upvotes: 2

Related Questions