Search code examples
ruby-on-railspostgresqlruby-on-rails-4database-migration

t.belongs_to and the effect on postgresql DB


class CreateCustomers < ActiveRecord::Migration
  def change
    create_table :customers do |t|
      t.belongs_to :user
      t.string :firstname
      t.string :surname
      t.timestamps
    end
  end

These are my models:

class Customer < ActiveRecord::Base
    belongs_to :user
end

class User < ActiveRecord::Base
  has_many :customers
end

Found the t.belongs_to :user to add a foreign key in the database. But when I check up my postgre database with pgadminIII, there is no foreign_key listed. The migration adds the user_id as it should, but no foreign_key listed.

Any explanation for that?

best regards denym

Edit: More information on the t.belongs_to

create_table :accounts do |t|
  t.belongs_to :supplier
  t.string :account_number
  t.timestamps
end

This is one example of it. From the railsguide ebook chapter 2.


Solution

  • It's the first time I see this belongs_to thing, but to ad an index on a column in migration you need to write

    t.belongs_to :user, index: true
    

    (mind new hash syntax)