【问题标题】:How do I indicate a unique constraint in my Rails model?如何在我的 Rails 模型中指示唯一约束?
【发布时间】:2017-08-28 15:08:47
【问题描述】:

我使用的是 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

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

【问题讨论】:

  • 三列分别是buyuser_idcrypto_currency_id?
  • 是的,没错。

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


【解决方案1】:

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

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

【讨论】:

  • 为什么需要创建迁移?根据我的表描述,唯一约束/索引已经在表中,不是吗?
  • @Dave 但是没有唯一的索引与所有三个的组合。不是吗?
  • @Dave 道歉,我看到已经有一个唯一索引。更新我的答案。
  • 嘿,我收到错误消息“未定义的方法 `validates_uniqueness_of' for UserNotification:Class”。这是版本的事情吗?我正在使用 Rails 5.0.4。
  • @Dave 你的UserNotification 模特怎么样?你能更新问题中的代码吗?
猜你喜欢
  • 1970-01-01
  • 2013-10-20
  • 2017-12-25
  • 2019-06-01
  • 1970-01-01
  • 2020-02-08
  • 1970-01-01
  • 2015-06-15
相关资源
最近更新 更多