我有一个简单的
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命令也许是最好的方法.