How to manage a primary key without auto-increment in Rails?

I have many situations where I want to have a primary key without auto-increment when using Rails.

Example: I have a one-to-one relationship between A and B. B describes some specific functions added to A, so it cannot exist without A. Thus, we have:

A has one B B belongs to A

Natural thinking will have B.A_id as the primary key. Therefore, I tried create_table b, :id=>falsein migration and set_primary_key :a_idin model B, but did not create the actual primary keys in the database. And I want them (as well as foreign keys), because the database will be used not only by this Rails application.

If I create primary keys with execution, they do not touch schema.rb, which hurts. Now I'm thinking of a workaround: I can live without the PK limit as long as there is a unique restriction for this column, so I can use add_index Rails in a migration that seems more elegant.

Any suggestions?

+3
source share
1 answer

fooobar.com/questions/462813 / ... try something like:

create_table(:b, :id => false) do |t|
  t.integer :a_id, :options => 'PRIMARY KEY'
end
+6
source

Source: https://habr.com/ru/post/1725503/


All Articles