0

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.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • Are you expecting to see a foreign key reference on the table the migrations create? – mrstebo Sep 20 '16 at 15:24
  • hmm, do I need to rake the db after I've added the associations in the active record files? I haven't done that. But, I would imagine I would need another key (foreign) that would point the products back to the categories. –  Sep 20 '16 at 15:49
  • I think you need to add foreign key: true on the column you want to make sure a foreign key is created in the database. See http://stackoverflow.com/questions/16257116/adding-foreign-key-to-a-rails-model – mrstebo Sep 20 '16 at 15:53

1 Answers1

2

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

Andy Gauge
  • 1,428
  • 2
  • 14
  • 25
  • Thanks! I've just tried that. Now I imagine my tables are connected. –  Sep 23 '16 at 14:50
  • Can I regenerate the products form to include this category automatically? Or do I have to insert the dropdown manually? –  Sep 24 '16 at 03:12
  • Generally, the scaffold is used to create a prototype. You generally update that prototype manually. I don't think the intention was to allow you to make changes to the models and regenerate the views. – Andy Gauge Sep 24 '16 at 20:38
  • hmm, I've edited the _form for my products to include the category reference. But the category reference for the product is not being written to the table. –  Sep 29 '16 at 00:29
  • Probably need to add to the permitted params in the controller. For a has, many you need to permit `:product_id => []` http://stackoverflow.com/a/17532811/5586783 – Andy Gauge Sep 29 '16 at 15:32