Ruby on Rails的在多个列的数据库中指定的唯一性 [英] ruby on rails specifying uniqueness in db across multiple columns

查看:218
本文介绍了Ruby on Rails的在多个列的数据库中指定的唯一性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,如下:

class EntityTag < ActiveRecord::Base
  attr_protected :user_id, :post_id, :entity_id

  belongs_to :user
  belongs_to :post
  belongs_to :entity

  validates :user_id, :presence => true
  validates :entity_id, :presence => true
  validates :post_id, :presence => true
end

我要谨防具有USER_ID,entity_id和的post_id的相同组合多行(例如,某行的唯一ID是所有这三个值)。

I want to guard against multiple rows which have the same combination of user_id, entity_id, and post_id (e.g. a unique ID for a row is all three of those values).

什么是我能传达给ActiveRecord的最简单的方法是什么?

What's the easiest way I can communicate that to ActiveRecord?

推荐答案

由于@dhruvg提到的:

As @dhruvg mentioned:

validates_uniqueness_of :user_id, :scope => [:entity_id, :post_id]

请注意,模型级别的唯一性验证无法保证在数据库中的唯一性。为了有一个,你应该把一个唯一索引在表上。

Do note that uniqueness validation on model level does NOT guarantee uniqueness in the DB. To have that, you should put a unique index on your table.

以下内容添加到您的迁移。

Add the following to your migrations.

add_index :entity_tags, [:user_id, :post_id, :entity_id], :unique => true

这篇关于Ruby on Rails的在多个列的数据库中指定的唯一性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆