我有带有电子邮件字段的构建器和用户模型,我想在两个模型中使电子邮件成为唯一的。当我放入Builder模型而不是用户模型时,验证方法下面的工作正常。
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,:recoverable, :rememberable, :trackable, :validatable, :confirmable
attr_accessible :email, :password, :password_confirmation, :remember_me,:confirmation_token, :confirmed_at, :confirmation_sent_at, :unconfirmed_email, :provider,:uid, :name, :oauth_token, :oauth_expires_at
validate :check_email_exists
def check_email_exists
if Builder.exists?(:email => self.email)
errors.add(:email,"User already exists with this email, try another email")
end
end
错误是:
NoMethodError in Devise::RegistrationsController#create
app/models/user.rb:30:in `check_email_exists'
{"utf8"=>"✓",
"authenticity_token"=>"EiFhJta51puZ7HZA3YzhopsKL2aJWllkl8geo3cL3gc=",
"user"=>{"email"=>"builder@gmail.com",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]"},
"commit"=>"Sign up"}
错误的原因是什么?我试图解决它很多天但没有成功。
这是我的构建器模型
class Builder < ActiveRecord::Base
devise :database_authenticatable, :registerable,
attr_accessible :email, :password, :password_confirmation, :remember_me,
validate :email_exists
def email_exists
if User.exists?(:email => self.email)
errors.add(:email,"User already exists with this email, try another email")
end
end
让abc@gmail.com已经存在于User,Builder注册表单将告诉用户已经存在尝试另一封电子邮件如果我在Builder注册表单中使用abc@gmail.com注册,这意味着email_exists工作正常构建器模型,但如果我签入用户模型,为什么抛出错误,尽管代码是正确的。
class User < ActiveRecord::Builder
发生错误:
退出
/home/rails/Desktop/realestate/app/models/user.rb:1:in <top (required)>': uninitialized constant ActiveRecord::Builder (NameError)
from /home/rails/.rvm/gems/ruby-1.9.3-p448/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:230:in
阻止constantize'
答案 0 :(得分:1)
从Builder
引用的错误看起来是指在ActiveRecord范围中定义的ActiveRecord::Associations::Builder
模块。
尝试使用::Builder
访问您的模型,所以:
if ::Builder.exists?(email: email)
答案 1 :(得分:0)
为什么不使用默认验证来实现唯一性
class User < ActiveRecord::Base
...
validates :email, :uniqueness => true, :message => "User already exists with this email, try another email"
...
end
同样在上面提到的代码中,您应该使用User模型而不是Builder
class User < ActiveRecord::Base
...
def check_email_exists
if User.exists?(:email => self.email)
errors.add(:email,"User already exists with this email, try another email")
end
end
...
end