In Ruby on Rails, if we created an "Animal" model and now want to have a "Dog", how do we do this?

let's say if we created a model

rails generate model animal name:string birthday:date 

and now we want to create another model for it (for example, Dog and Cat), should we again use the rails generate model or just add the files themselves? How do we indicate that Dog should inherit from Animal if we use rails generate model ?

I think that if we use rails generate model instead of adding the model files themselves, unit test files and archive files will be created. A migration file is also added, unless it uses MongoDB, then there will be no migration file.

+6
inheritance ruby-on-rails single-table-inheritance rails-models
source share
2 answers

If Dog , Cat and the other subclasses you plan on will not deviate from the Animal model, you can STI (Single Table Inheritance) here.

To do this, add the String column to Animal . And then you can:

 class Dog < Animal end class Cat < Animal end >> scooby = Dog.create(:name => 'Scooby', :date => scoobys_birthdate) => #<Dog id: 42, date: "YYYY-MM-DD", type: "Dog"> 

To create a Dog model

 $ script/generate model Dog --skip-migration 

And then change (usually app/models/dog.rb ):

 class Dog < ActiveRecord::Base 

to

 class Dog < Animal 
+7
source share

As far as I know, you cannot specify a superclass when creating a model. However, generators are just a step further to create your classes. You can create a model class as normal and simply change the superclass in the generated model file. Other places where inheritance relationships should be indicated should not be indicated for the generated files (for example, super- or subclasses are not indicated in devices and unit tests).

So:

 script/generate model Dog 

Then change:

 class Dog < ActiveRecord::Base 

in

 class Dog < Animal 

If you want to generate a model that inherits Animal using unidirectional inheritance of the table, then you can specify -skip migrations in the script / generate call (although you may need to go through, for example, specific columns of the animal table, and you will need to add the type column of the row type in the animal table).

+2
source share

All Articles