V
V
Vladislav Sofienko2017-04-02 16:55:00
Ruby on Rails
Vladislav Sofienko, 2017-04-02 16:55:00

How to create linked table in migration?

Is it possible to prescribe the creation of a table with the creation of a one-to-many relationship in the migration? How?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Ivanov, 2017-04-02
@sofvlad

A one-to-many relationship is the presence in each row of one table of an indication of the row ID of another table.
It is written in the migration as belongs_to
For example

class CreateProduct < ActiveRecord::Migration[5.0]
  def change
    create_table :products do |t|
      t.belongs_to :user, foreign_key: true
 # ... остальные поля
      t.timestamps
    end
  end
end

Here a product table is created with a link to the users table (of course, the users table should already exist). An index and a foreign key will be automatically created.
The user-product relationship will be one-to-many

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question