Hopstream
Hopstream

Reputation: 6451

Single table/model with secondary models?

If I have a model called Keyboard. Is there a way to create two sub models called MechanicalKeyboard and ChicletKeyboard?

The sub models have slightly different controller and view logic, so I want to break those out of the main model -- but there will still be only one table/main model.

The sub models will use the same attributes. I tried to use an enum for this, but separate controller and views make more sense.

Is that possible in Rails?

Upvotes: 0

Views: 27

Answers (1)

Wikiti
Wikiti

Reputation: 1636

Yes, it's possible. It's called Single Table Inheritance. You just need to add a new attribute to your Keyboard model called type:

class AddTypeToKeyboards < ActiveRecord::Migration
  def change
    add_column :keyboards, :type, :string
  end
end

Then, you define your tables inheriting them from your main model:

# app/models/mechanical_keyboard.rb
class MechanicalKeyboard < Keyboard
  # Custom validations and methods go here.
end

# app/models/chiclet_keyboard.rb
class ChicletKeyboard < Keyboard
  # Custom validations and methods go here.
end

They'll use the very same table keyboards, and share the same attributes (columns). To create, update, query or manage keyboards, you can use whatever class you want. Rails will handle the type value automatically. For example, to retrieve all the mechanical keyboards, you can use MechanicalKeyboard.all, which is equivalent to Keyboard.where(type: 'MechanicalKeyboard').

Upvotes: 1

Related Questions