Modeling inheritance with Ruby/Rails ORMs

前端 未结 2 544
情歌与酒
情歌与酒 2021-01-27 06:29

I\'m trying to model this inheritance for a simple blog system

Blog has many Entries, but they may be different in their nature. I don\'t want to model the

2条回答
  •  自闭症患者
    2021-01-27 07:04

    You can handle this easily using ActiveRecord STI. It requires you to have a type field in your Entries table. This way you can define your models like this:

    def Blog > ActiveRecord::Base
      has_many :entries
    
      def articles
        entries.where('Type =', 'Article')
      end
    
      def quotes
        entries.where('Type =', 'Quote')
      end
    
      def medias
        entries.where('Type =', 'Media')
      end
    
    end
    
    def Entry > ActiveRecord::Base
      belongs_to :blog
    end
    
    def Article > Entry
    end
    
    def Quote > Entry
    end
    
    def Media > Entry
    end
    

提交回复
热议问题