user2701001
user2701001

Reputation:

rails associations between two tables

I've got two tables in my Postgres database: categories and products.

I have a one to many relationship defined, one category can have many products.

After I've defined these in the two models in Rails, is there something else I need to do to the tables? I still have only the primary key that Rails defined when I set up each model separately.

Upvotes: 0

Views: 1153

Answers (1)

Andy Gauge
Andy Gauge

Reputation: 1428

You can run a migration generator with the right parameters to set up the foreign key.

bin/rails generate migration AddCategoryRefToProducts category:references

This assumes you have a Product model and Category model with these associations:

#product.rb
belongs_to :category

#category.rb
has_many :products

Run rake db:migrate to complete the process

When you look at your db/migrate directory you will see a file that contains an add_reference line within a def change block. Here's the reference for that method: Rails API. The syntax for the standalone generator is from the Rails Guides

Upvotes: 2

Related Questions