I
I
Ilnar252018-02-27 12:18:05
PostgreSQL
Ilnar25, 2018-02-27 12:18:05

How to write uniqueness in database on rails?

We have such a table in schema.rb

create_table "menus_products", force: :cascade do |t|
    t.bigint "menu_id"
    t.bigint "product_id"
    t.index ["menu_id"], name: "index_menus_products_on_menu_id"
    t.index ["product_id"], name: "index_menus_products_on_product_id"
  end

How to write uniqueness for each record (not to confuse uniqueness for a column) at the database level (postgresql). It is desirable that the record be visible in migrations (adding uniqueness to a table or creating a new one with uniqueness, there is no difference), and not commands for the psql terminal (is this possible?). There is no MenusProduct model, only a join table. In general, what is the right thing to do?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kozlov, 2018-02-27
@Ilnar25

Create a composite unique index

add_index :menus_products, %i[menu_id product_id], unique: true

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question