How to define a “unique” constraint on a column of MySQL table in Ruby on Rails 3?

蓝咒 提交于 2019-12-21 03:48:10

问题


I have a simple MySQL table with one column: name.

I would like to define a unique constraint on this column.

I can do:

class MyModel < ActiveRecord::Base
  validates_uniqueness_of :my_column_name
end

but it will work only at the application level, not at the database level.

What would you suggest ?


回答1:


This is not super-helpful, but it looks like there is not a great answer for enforcing uniqueness at the database level. From the 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.

It looks like running the SQL command yourself with the ActiveRecord execute method may be the best way to go if you really want to enforce uniqueness in the database.




回答2:


Add a unique constraint to the database itself using:

add_index :my_models, :my_column_name, unique: true

...through a migration (and you might want to make that my_column_name not accept any null values too:

class CreateMyModels < ActiveRecord::Migration
  def change
    create_table :my_models do |t|
      t.string :my_column_name, null: false

      t.timestamps
    end

    add_index :my_models, :my_column_name, unique: true

  end
end


来源:https://stackoverflow.com/questions/4405471/how-to-define-a-unique-constraint-on-a-column-of-mysql-table-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!