Home > Mobile >  Ruby on Rails throws Unknown validator: 'UniqueValidator' when adding unique constraint
Ruby on Rails throws Unknown validator: 'UniqueValidator' when adding unique constraint

Time:10-07

I am experienced with Ruby, but completely new to Rails (7.0.4). I am trying to set up basic validation for my test database.

When my app>model>language.rb file looks like this, it works:

class Language < ApplicationRecord
    # attr_accessible :code, :dev_name, :dev_description

    validates :code,    :presence => true,
                        format: { with: /\A([A-Z]{3}(?:\:[a-z]{2,4})?)\z/ }
end

But when I try to add :unique => true constraint:

class Language < ApplicationRecord
    # attr_accessible :code, :dev_name, :dev_description

    validates :code,    :presence => true,
                        :unique => true,
                        format: { with: /\A([A-Z]{3}(?:\:[a-z]{2,4})?)\z/ }

I get the following error:

Unknown validator: 'UniqueValidator'
Extracted source (around line #4):

Rails.root: D:/RORdev/project
Application Trace | Framework Trace | Full Trace
app/models/language.rb:4:in `<class:Language>'
app/models/language.rb:2:in `<main>'
app/controllers/languages_controller.rb:6:in `index'
Exception Causes
NameError: uninitialized constant Language::UniqueValidator validator = key.include?("::") ? key.constantize : const_get(key) ^^^^^^^^^

My migration file:

class CreateLanguages < ActiveRecord::Migration[7.0]
  def change
    create_table :languages do |t|
      # id by default
      t.string :code, index: { unique: true }
      t.string :dev_name
      t.text :dev_description

      t.timestamps
    end
  end
end

Before resetting, the database had the following shape:

0   
id  1
code    "POL"
dev_name    "Polish"
dev_description "standard modern Polish language"
created_at  "2022-10-06T10:29:55.539Z"
updated_at  "2022-10-06T10:29:55.539Z"
url "http://localhost:3000/languages/1.json"
1   
id  2
code    "ENG"
dev_name    "English"
dev_description "standard modern English language"
created_at  "2022-10-06T10:49:21.163Z"
updated_at  "2022-10-06T11:02:54.885Z"
url "http://localhost:3000/languages/2.json"

I have completely no idea how to diagnose this issue.

CodePudding user response:

I think you need to use

validates :code, presence: true, uniqueness: true

instead of unique: true

  • Related