4

I have a basic Ruby app that I am building with Sinatra, Datamapper and has user authentication using OAuth. When I receive the data back from the Oauth service, I save a record of a new user in an sqlite3 db.

What I don't know how to do is how to go about verifying the user record doesn't already exist on the user database table. I can use the user's unique id (uid) to cross check whether the uid is already stored, but I am just unsure where to do this.

I have 2 classes and a /callback route. The User class is the db model, and an Authentication class has assorted methods for connecting to the OAuth, and the /callback route which will have the Authentication.save method being called.

Should I be checking for an existing record within the Authentication.save method and return a boolean or something else? Create a new method in Authentication that would be like Authentication.exists? (and what would that look like?) Or should I be checking within the /callback route?

I apologize if this wasn't 100% clear, I am having a difficult time describing my issue and am an absolute Ruby beginner...

kylemac
  • 623
  • 2
  • 7
  • 15

1 Answers1

2

Just before creating your new user, you should try to check if an user with the same login and email (for example) exists :

require 'dm-aggregates'

user=User.new
user.login=your_login_data_returned_by_oauth
user.email=your_email_data_returned_by_oauth
# And so on...
user.save if User.count(:login=>user.login, :email=>user.email) == 0
Yoann Le Touche
  • 1,280
  • 9
  • 13
  • 3
    I'm not sure but it looks like to, potentially, fetch a whole full filled collection of objects to check the existence of a register is not an optimized solution. I'll replace the condition with `if User.count(:login=>user.login, :email=>user.email) == 0`. – fguillen Nov 02 '11 at 14:31
  • The User.count is better, I don't know why I didn't mention it as it is the way I always do that sort of things. – Yoann Le Touche Nov 14 '11 at 12:52
  • On a second thought , user.count doesnt work : http://stackoverflow.com/questions/14393004/ruby-datamapper-count-not-working . I got bitten by it as well – codeObserver Jun 20 '13 at 05:20