Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby On Rails- Multiple references in a model

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?

like image 379
Danielle Rose Mabunga Avatar asked Oct 19 '15 10:10

Danielle Rose Mabunga


1 Answers

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 :

  • http://guides.rubyonrails.org/command_line.html#rails-generate
  • http://railsguides.net/advanced-rails-model-generators/
like image 168
Caillou Avatar answered Oct 21 '22 11:10

Caillou