Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to enter value A in Model X only if value A exists in Model Y?

I'm trying to build a registration module where user can only register if their e-mail is already in an existing database.

Models:

  1. User
  2. OldUser

The condition on User will be

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

This is really simple to do in PHP where I can just run a function to execute a mysql query. However, I couldn't figure out how to do it on Rails. It looks like I have to create a custom validator function but seems to be overkilled for a such simple condition.

It should be pretty simple to do. What have I missed?

Any pointer?

Edit 1:

This solution by dku.rajkumar 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 cases like this, is it better to do validation in the model or at the controller?

like image 389
John Kimbell Avatar asked Dec 10 '25 02:12

John Kimbell


1 Answers

you can do it as

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: validation in model, so the validation will be done while calling 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
like image 141
dku.rajkumar Avatar answered Dec 12 '25 22:12

dku.rajkumar