2017-11-08 1 views
1

Ich habe die Datei folgende /app/validators/hex_color.rb in meiner Rails-Anwendung:uninitialized konstant, wenn einschließlich Validator

module Validators 
    class HexColorValidator < ActiveModel::EachValidator 

    def validate_each(record, attribute, value) 
     unless value =~ /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/i 
     record.errors[attribute] << (options[:message] || 'must be a valid CSS hex color code') 
     end 
    end 

    end 
end 

Und dann in meinem Modell an: /app/models/brand_theme.rb ich habe:

class BrandTheme < ApplicationRecord 

    include Validators 

    validates :brand_1, presence: true, hex_color: true 

end 

Aber ich bekomme die Fehlermeldung:

uninitialized constant BrandTheme::Validators 

Warum ist der Validator nicht enthalten? Ich habe versucht, Server auch zurückzusetzen, aber das gleiche Problem kommt auf.

+0

Sie haben wahrscheinlich 'app/validators' nicht zu' autoload_paths' hinzugefügt. –

+0

@MarekLipka Ich hatte den Eindruck, alles unter 'app' ist in Rails automatisch geladen? Wir haben mehrere andere Ordner darunter, die automatisch geladen werden. – Cameron

+0

Nun, ist es nicht. Sie müssen es manuell tun. –

Antwort

1

Ihre Klasse wird nicht geladen, weil Sie nicht den rails convention folgen. Sie sollten es nicht in das Validierungsmodul einfügen. Und ich würde mit Modul HexColor gehen ... nicht die Klasse.

die Lösung So, hier ist ... Datei /app/validators/hex_color_validator.rb:

module HexColorValidator < ActiveModel::EachValidator 
    def validate_each(record, attribute, value) 
    unless value =~ /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/i 
     record.errors[attribute] << (options[:message] || 'must be a valid CSS hex color code') 
    end 
    end 
end 

class BrandTheme < ApplicationRecord 
    include HexColorValidator 

    validates :brand_1, presence: true, hex_color: true 
end 

Dann wird es automatisch geladen werden. Wenn Sie mehrere Module benötigen, gehen Sie mit Modul als Unterordner von app/validators oder fügen Sie einfach mehrere separate Module ein

+0

Während Sie validate_each ... verwenden, müssen Sie vielleicht mit 'extend HexColorValidator' gehen – AntonTkachov

Verwandte Themen