Ruby On Rails - Multiple Model Links

I have a model with several relationships to the other three models, from one to many relationships. I manually created the Model class this way

class Voter < ActiveRecord::Base
  belongs_to :city
  belongs_to :grp
  belongs_to :profession
end

I have two questions about this,

First, How do I create a multi-relationship migration? This is my migration file

 class CreateVoters < ActiveRecord::Migration
  def change
    create_table :voters do |t|
     t.string :firstname
     t.string :middlename
     t.string :lastname
     t.text :comments
     t.date :birthday
     t.references :city, index: true, foreign_key: true
     t.timestamps null: false
   end
 end
end

I'm going to make this way

   t.references :city, index: true, foreign_key: true
   t.references :grp, index: true, foreign_key: true
   t.references :profession, index: true, foreign_key: true

Is it correct?

The second question is that instead of manually changing the migration file, you can run "rails generate model" ........ with multiple links so that multiple links are automatically added to the migration file? maybe how are you doing this?

+4
source share
1 answer

. :

rails generate model voter city:references grp:references profession:references firstname:string middlename:string lastname:string comments:text birthday:date

.

//voter.rb:

class Voter < ActiveRecord::Base
  belongs_to :city
  belongs_to :grp
  belongs_to :profession
end

db/migrate/20151019104036_create_voters.rb:

class CreateVoters < ActiveRecord::Migration
  def change
    create_table :voters do |t|
      t.references :city, index: true, foreign_key: true
      t.references :grp, index: true, foreign_key: true
      t.references :profession, index: true, foreign_key: true
      t.string :firstname
      t.string :middlename
      t.string :lastname
      t.text :comments
      t.date :birthday    
      t.timestamps null: false
    end
  end
end

:

+6

Source: https://habr.com/ru/post/1612226/


All Articles