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

前端之家收集整理的这篇文章主要介绍了如何在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命令也许是最好的方法.

原文链接:https://www.f2er.com/ruby/272054.html

猜你在找的Ruby相关文章