Rails: how to enter the value A into model X only if the value A exists in model Y?

I am trying to create a registration module where a user can register only if their email is already in the existing database.

Models:

  • User
  • Olduser

The condition for the user will be

if OldUser.find_by_email(params[:UserName]) exists, allow user registration.
If not, then indicate error message.

This is really easy to do in PHP, where I can simply run the function to execute the mysql query. However, I could not figure out how to do this on Rails. It seems like I should create a custom validator function, but it seems too overpriced for such a simple condition.

It should be pretty simple. What did I miss?

Any pointer?

Edit 1:

This dku.rajkumar solution works with a slight modification:

validate :check_email_existence
    def check_email_existence
      errors.add(:base, "Your email does not exist in our database") if OldUser.find_by_email(self.UserName).nil?
    end

For such cases, is it better to check in the model or controller?

+3
3

if OldUser.find_by_email(params[:UserName])
   User.create(params) // something like this i guess
else
   flash[:error] = "Your email id does not exist in our database."
   redirect_to appropriate_url
end

UPDATE: , User.create

class User < ActiveRecord::Base

  validates :check_mail_id_presence

// other code
// other code

  private

  def check_mail_id_presence
     errors.add("Your email id does not exist in our database.") if OldUser.find_by_email(self.UserName).nil?
  end

end
+1

Bellow - ... /app/controller/UsersController , .


 def new
  @user = User.new
 end
 def create
  @user = User.new(params[:user])
  @old_user = User.find_by_email(user.email)
  if @old_user 
     if @user.save
      # Handle successful save
     else
     render 'new' # and render some error message telling why registration was not succeed 
     end
  else
   # render some page with some sort of error message of 'new' new users
  end
 end

Update: :

0

All Articles