Question

I have Builder and User model with email field, I want to make email as unique in both model. Below validation method is working fine when i put in Builder model but not in User model.

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 

Error is:

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"}

What is the reason of error? I am trying to resolve it from lot of days but unsuccess.

This is my builder model

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 

let abc@gmail.com is already there in User, Builder sign up form will tell user already exists try another email if I sign up with abc@gmail.com in Builder sign up form, that means email_exists is working fine in builder model but why throws error if i check in User model, although code is right.

class User < ActiveRecord::Builder

Error occurs: Exiting /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:inblock in constantize'

Was it helpful?

Solution

It looks like from the error that Builder is referring to the ActiveRecord::Associations::Builder module which is defined in the ActiveRecord scope.

Try accessing your model with ::Builder, so:

  if ::Builder.exists?(email: email)

OTHER TIPS

Why don't you use default validation for uniqueness

class User < ActiveRecord::Base
  ...
  validates :email, :uniqueness => true, :message => "User already exists with this email, try another email"
  ...
end

Also in above menioned code, you should use User model instead of 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top