ruby-on-railsrubyactiverecordassociationssti

Using a has_many association with a single table inheritance model in rails


I'm trying to create a simple has_many association between my Game and DLC models. The challenge I'm facing is that since there's no DLC table because of the single table inheritance, there's no way to insert a game_id. So if I were to do the following I'd get this error:

game = Game.create
game.dlcs

SQLite3::SQLException: no such column: games.game_id

Here is how my models are currently setup:

class Game < ActiveRecord::Base
    has_many :dlcs
end

class DLC < Game
    belongs_to :game
end

Note: DLC refers to downloadable content


Solution

  • The simplest alternative would be to just use self-joins and add a parent_id column to games.

    class Game < ActiveRecord::Base
      has_many :dlcs unless self.name == 'DLC'
    end
    
    class DLC < Game
      belongs_to :game, foreign_key: :parent_id
    end
    

    If that's absolutely unthinkable you can create a join table.

    # game_id: int
    # dlc_id: int
    class GameExtension
      belongs_to :game
      belongs_to :dlc
    end
    
    class Game < ActiveRecord::Base
      has_many :game_extensions
      has_many :dlcs, though: :game_extensions
    end
    
    class DLC < Game
      has_many :game_extensions
      belongs_to :game, though: :game_extensions
    end