I have Model with multiple relationships to another three Models in a one to many relationships.I manually created a 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 the migration with multiple relationship? 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 am thinking to do 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 proper?
The second question is, instead of manually altering the migration file is it possible to run 'rails generate model' ........with multiple references, so that multiple references automatically added in migration file ?If it is possible, how do you do it?
You had it right. You can absolutely generate a model with its migration in one command :
rails generate model voter city:references grp:references profession:references firstname:string middlename:string lastname:string comments:text birthday:date
This will generate your model with your relations and the right migration, all at once.
app/models/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
Documentation :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With