How to implement Active Record inheritance in Ruby on Rails?

后端 未结 3 1236
花落未央
花落未央 2020-12-01 02:52

How to implement inheritance with active records?

For example, I want a class Animal, class Dog, and class Cat.

How would the model and the database table ma

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 03:26

    Models:

    class Animal < ActiveRecord::Base; end
    class Dog < Animal; end
    class Cat < Animal; end
    

    Migration:

    class CreateAnimals < ActiveRecord::Migration
      def self.up
        create_table :animals do |t|
          # Other attributes...
          t.string :type
        end
      end
    
      def self.down
        drop_table :animals
      end
    end
    

提交回复
热议问题