Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

ruby - 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 using Rails ActiveRecord migrations? I'm using PostgreSQL as my DB.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The currently accepted answer on this isn't really accurate as it doesn't add a database foreign key. It's just adding integer columns.

In Rails 4.2.x, the current approach is:

http://guides.rubyonrails.org/active_record_migrations.html#foreign-keys

Create a migration:

rails generate migration migration_name

For existing columns, in the migration add the foreign keys like this:

class MigrationName < ActiveRecord::Migration
  def change
    add_foreign_key :business_hours, :businesses
    add_foreign_key :businesses, :users
  end
end

For Rails 4.x or if you're adding a new column and want it to be a foreign key you can do this, where you probably also want to specify the index as true, but that's not part of the requirement for the foreign key:

http://edgeguides.rubyonrails.org/active_record_migrations.html#creating-a-migration

class MigrationName < ActiveRecord::Migration
  def change
    add_reference :business_hours, :business, index: true, foreign_key: true
    add_reference :businesses, :user, index: true, foreign_key: true
  end
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...