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}),
nil).run()
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!