Inserting users on a branch in RethinkDB


This post still working for you?

It's been a while since this was posted. Hopefully the information in here is still useful to you (if it isn't please let me know!). If you want to get the new stuff as soon as it's out though, sign up to the mailing list below.

Join the Mailing list

If you’ve ever wondered how to insert a user (or any record really) on the condition that a user with a given property didn’t exist, here you go:

(Note this is in ruby, as the latest project I’m working on is a Sinatra app :))

inserted = r.branch(r.table(‘users’).filter({:username => username}).count().eq(0),

r.table(‘users’).insert({:username => username, :email => email}),


It seems to be at least a LITTLE less race-condition prone than doing the check and acting on it. This took me far longer than it should have, given the guys at rethinkdb‘s wonderful syntax and driver design… Looks like I’ve still got a ways to go.

[EDIT] – as an awesome commenter has pointed out, there actually doesn’t need to be a .run() in the first statement of the branch, so that’s been removed!

Like what you're reading? Get it in your inbox