1

I was going through Rails association link. But I am not able to understand how the association works. I am using mysql db.

These are the files I generated:

user.rb

class User < ActiveRecord::Base
    has_many :orders
end

order.rb

class Order < ActiveRecord::Base
    belongs_to :user
end

20150911181301_create_orders.rb

class CreateOrders < ActiveRecord::Migration
  def change
    create_table :orders do |t|
      t.string :content
      t.integer :user_id

      t.timestamps null: false
    end
  end
end

20150911181351_create_users.rb

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email

      t.timestamps null: false
    end
  end
end

First I was expecting db:migrate will generate some foreign key relationship itself but it did not happen. Then I thought may be rails manages it internally but when I deleted a user through rails c , it did not delete corresponding orders from the order table.

Where is my understanding incorrect? Also give me some links which explains how does this works?

Sreeraj Chundayil
  • 5,548
  • 3
  • 29
  • 68

2 Answers2

1

It's debatable but the traditional 'Rails way' is to manage model-related things like defaults, foreign keys, and triggers is at the ActiveRecord level instead of in the database.

That said, you're free to add a foreign key for referential integrity in a migration using the following:

add_foreign_key :orders, :users

More information is available in the Rails Guides.

The 'Rails way' to automatically destroy child objects when the parent is destroyed is to specify the :dependent strategy on the child collection. There is a great Stackoverflow discussion here going into detail about the two :dependentoptions: :destroy vs :delete_all.

Community
  • 1
  • 1
madcow
  • 2,567
  • 14
  • 31
1

Everything is in the docs

-You should note that "In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations."

-You should also note that when it comes to associations, Rails needs you to tell it that asides two models being related with belongs_to and has_many, you want the associated model to be deleted when it's parent model is deleted. That is where the dependent: :destroy comes in.

Now all you need to do in your code for orders related to a user to get deleted when the user is:

class User < ActiveRecord::Base
    has_many :orders, dependent: :destroy
end

Source: Rails Guides

ollaollu
  • 473
  • 7
  • 19