title: atomic insert or increment in ActiveRecord/Rails
body: <p>What's the best way to implement an atomic insert/update for a model with a counter in Rails? A good analogy for the problem I'm trying to solve is a "like" counter with two fields: </p>
  
  <pre><code>url   : string
  count : integer
  </code></pre>
  
  <p>Upon insert, if there is not currently a record with a matching url, a new record should be created with count 1; else the existing record's <code>count</code> field should be incremented.</p>
  
  <p>Initially I tried code like the following:</p>
  
  <pre><code>Like.find_or_create_by_url("http://example.com").increment!(:count)
  </code></pre>
  
  <p>But unsurprisingly, the resulting SQL shows that the <code>SELECT</code> happens outside the <code>UPDATE</code> transaction:</p>
  
  <pre><code>Like Load (0.4ms)  SELECT `likes`.* FROM `likes` WHERE `likes`.`url` = 'http://example.com' LIMIT 1
  (0.1ms)  BEGIN
  (0.2ms)  UPDATE `likes` SET `count` = 4, `updated_at` = '2013-01-17 19:41:22' WHERE `likes`.`id` = 2
  (1.6ms)  COMMIT
  </code></pre>
  
  <p>Is there a Rails idiom for dealing with this, or do I need to implement this at the SQL level (and thus lose some portability)?</p>