Ruby on Rails and Database Associations


I'm new to the Ruby world, and there is something unclear to me in defining associations between models. The question is: where is the association saved?

For example, if i create a Customer model by executing:

generate model Customer name:string age:integer

and then i create an Order model

generate model Order description:text quantity:integer

and then i set the association in the following way:

class Customer < ActiveRecord::Base
  has_many :orders

class Order < ActiveRecord::Base
  belongs_to :customer

I think here is missing something, for example the foreign key between the two entities. How does it handle the associations created with the keywords "has_many" and "belongs_to" ?


Whenever you generate your order, you can do:

generate model Order description:text quantity:integer customer:references

And it will automatically create the foreign key in the migration for you. The rails convention is that every row will have a primary key called "id", and the foreign key is the table it is referencing, followed by an underscore, then id. So in this case the orders table will have an attribute called "customer_id"

Since you've already generated yours, you should create a new migration script that adds an integer column called "customer_id" to your orders table.

You don't want to modify an existing migration. Just create a new one that adds the column.

class add_customer_id_to_orders < ActiveRecord::Migration
  def self.up
    add_column :orders, :customer_id, :integer

  def self.down
    remove_column :orders, :customer_id

Note: If you've already done something to create data in your database, this is going to result in some null foreign keys, which you'll want to fix, or just delete and create new data.