user984621
user984621

Reputation: 48443

Rails - how to avoid validation errors in creating a record in a model?

I am working on Facebook authentication for Devise and I stumbled upon one problem - when will try to sign up someone with Facebook email that is already in the system, I get an error (which is partially correct).

I would need to redirect this user back to the homepage and there to print out this issue, but at the moment I am having this message printed as an error (on localhost).

Here's how I am doing that (user model):

def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
    data = access_token.extra.raw_info

    if user = User.where(:provider => 'facebook', :uid => data.id).first
      user
    else # Create a user with a stub password. 
      user = User.create!(:first_name => data.first_name,
                          :last_name => data.last_name,
                          :email => data.email, 
                          :password => Devise.friendly_token[0,20],
                          :provider => 'facebook',
                          :uid => data.id,
                          :terms_of_use => true) 
    end
    return user if user
  end

How to redirect the user on a page where would be printed out the validation messages?

Thanks

Upvotes: 0

Views: 105

Answers (1)

AnkitG
AnkitG

Reputation: 6568

Why don't you have something like this in your model and controller

Return just the user object from the method

def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
    data = access_token.extra.raw_info
    #Look for the first user with provider: :facebook & uid: data.id,
    #If now user is there go ahead and create one with first_or_create.
    user = User.where(:provider => 'facebook', :uid => data.id).first_or_create do |user|
           user.first_name = data.first_name,
           user.last_name = data.last_name,
           user.email = data.email,
           user.password = Devise.friendly_token[0,20],
           user.provider = 'facebook',
           user.uid = data.id,
           user.terms_od_use = true
          end
  end

Controller

def sign_in_method #dummy method
  user = User.find_for_facebook_oauth(access_token, signed_in_resource=nil)
  if user.valid?
    redirect success_url #any url where u want to redirect on success 
  else user.errors
     redirect root_url, error: user.errors.full_messages.join(', ')
  end
end

Upvotes: 1

Related Questions