如何在Ruby on Rails 3中的MySQL表列上定义“唯一”约束?

我有一个简单的 MySQL表与一列:名称.

我想在这个列上定义一个唯一的约束.

我可以:

class MyModel < ActiveRecord::Base
  validates_uniqueness_of :my_column_name
end

但它只能在应用程序级别工作,而不是数据库级别.

你会建议什么

解决方法

这不是超级有用的,但是看起来在数据库级别上强制执行唯一性并不是一个很好的答案.从 Rails migration guide

The Active Record way claims that intelligence belongs in your models,not in the database. As such,features such as triggers or foreign key constraints,which push some of that intelligence back into the database,are not heavily used.

Validations such as validates_uniqueness_of are one way in which models can enforce data integrity.

Although Active Record does not provide any tools for working directly with such features,the execute method can be used to execute arbitrary sql.

如果您真的要在数据库中强制执行唯一性,那么ActiveRecord execute方法就像自己运行sql命令也许是最好的方法.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...