如何在我的 Rails 模型中指示唯一约束?

How do I indicate a unique constraint in my Rails model?

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

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)

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

  if @user_notification.save
...
  else
    format.html { render action: "index" }
    puts "full messages: #{@user_notification.errors.full_messages}"
    format.json { render json: @user_notification.errors, status: :unprocessable_entity }
    format.js { render json: { errors: @user_notification.errors, success: false }, content_type: 'application/json' }
  end

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

我相信您希望 buy 上的独特性与 user_idcrypto_currency_id 的组合,然后在您的 UserNotification 模型中尝试以下

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