Search code examples
ruby-on-railsactiverecordmodels

Inheriting off an active record model in Ruby on Rails


I was hoping I could inherit off an activerecord model, and use the subclass as I could the parent class. This does not appear to be the case, the AR relationships do not appear to work for the subclass.

class Manager < User
  belongs_to :shop
end

class Shop < ActiveRecord::Base
  has_many :managers
end

class PremiumShop < Shop
end

and

@premium_shop = manager.shop # Finds the shop.
@premium_shop = manager.premium_shop # Does not find the shop, NilClass:Class error

Is it possible to make this work?


Solution

  • The shop method exists for some instance of the Manager class because of the association you defined through the belongs_to. You have no premium_shop method defined on your Manager model, thus the NilClass error.

    If you want to define such an association for the PremiumShop class, you must explicitly specify this.

    belongs_to :premium_shop, class_name: "PremiumShop", foreign_key: :shop_id
    

    Depending on your needs, you might also consider researching "rails single table inheritance".