2013-01-25 36 views
1

我從client_side_validations頁面複製了代碼。我有錯誤 undefined method validates_email for #<Class:0x007ff3382428a8> 當我把includes ::Validations放在我的模型中時,這個錯誤消失了,但驗證完全不起作用。客戶端驗證未定義的方法`validates_email'

應用程序/驗證/ email_validator.rb

class EmailValidator < ActiveModel::EachValidator 
    def validate_each(record, attr_name, value) 
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i 
    record.errors.add(attr_name, :email, options.merge(:value => value)) 
    end 
    end 
end 

# This allows us to assign the validator in the model 
module ActiveModel::Validations::HelperMethods 
    def validates_email(*attr_names) 
    validates_with EmailValidator, _merge_attributes(attr_names) 
    end 
end 

配置/語言環境/ en.yml

# config/locales/en.yml 
en: 
    errors: 
    messages: 
     email: "Not an email address" 

應用程序/資產/ Javascript角/ rails.validations.customValidators.js

// The validator variable is a JSON Object 
// The selector variable is a jQuery Object 
window.ClientSideValidations.validators.local['email'] = function(element, options) { 
// Your validator code goes in here 
if (!/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i.test(element.val())) { 
// When the value fails to pass validation you need to return the error message. 
// It can be derived from validator.message 
return options.message; 
} 
} 

models/comment.rb

class Comment < ActiveRecord::Base 
    attr_accessible :content, :email, :ip, :name, :post_id 
    belongs_to :post 
    validates_presence_of :content, :email, :post_id, :name 
    validates_email :email 
end 

回答

0

我沒有看到你包括你的模塊。另外,根據你放置模塊的位置,你有時需要「需要」它。而且,嘗試:

include <Module name> 

代替

includes <Module name> 

希望這將有助於