如何在Rails模型中指明唯一约束?

时间:2017-08-28 15:08:48

标签: ruby-on-rails model save ruby-on-rails-5 unique-constraint

我正在使用Rails 5.0.4(和PostGres 9.5)。在我的模型中,我有三个列的唯一约束

scripts

如何在我的模型中指出存在这种唯一约束,以便在我去保存模型时

cindex=# \d user_notifications;
                               Table "public.user_notifications"
       Column       |  Type   |                            Modifiers
--------------------+---------+-----------------------------------------------------------------
 id                 | integer | not null default nextval('user_notifications_id_seq'::regclass)
 user_id            | integer |
 crypto_currency_id | integer |
 price              | integer | not null
 buy                | boolean | not null
Indexes:
    "user_notifications_pkey" PRIMARY KEY, btree (id)
    "uk_user_notifications" UNIQUE, btree (user_id, crypto_currency_id, buy)
    "index_user_notifications_on_crypto_currency_id" btree (crypto_currency_id)
    "index_user_notifications_on_user_id" btree (user_id)

是否保存了正确的错误,表明违反了唯一约束?

1 个答案:

答案 0 :(得分:0)

我认为您希望在buyuser_id的组合crypto_currency_id上保持唯一性,然后在您的UserNotification模型中尝试以下

validates_uniqueness_of :buy, scope: [:user_id, :crypto_currency_id]