kmcgrady kmcgrady - 7 months ago 16
Ruby Question

Adding foreign key to a rails model

I'm quite new to rails and have been trying to work this out all night with no luck.

I have created 3 models:

users
,
businesses
, and
business_hours
. I have also added the associations (
business_hours belongs_to businesses which belongs_to users
) and (
user has_one business which has_many business_hours
).

Reading through the docs online it seems I now need to create the foreign keys for these relationships in my DB tables. How do I do this? Can I do it users migrations? I'm using PostgreSQL as my DB.

Answer

First of all when you use belongs_to method don't use s at the end of the word: business_hours belongs_to business which belongs_to user.

Now create a migration:

rails generate migration migration_name

And in migration add columns:

class MigrationName < ActiveRecord::Migration
  def change
    add_column :business_hours, :business_id, :integer
    add_column :businesses, :user_id, :integer
  end
end

Run rake db:migrate. That's it.