title: Rails Override Save To Perform Selective Update
body: <p>I am working on a Rails 3.2.8 application that uses a homegrown REST API to insert new data.  The insertion logic is generic for every endpoint and results quite simply in a call to Model.save.  </p>
  
  <p>For one of the model types I would like to first check if a pre-existing record exists and if so, update as opposed to insert.  If the code allowed me to interact at the Controller level this would be easy through the use of find_or_create_by, however (I think) my only option is to override the save method in the Model or use a before_save callback.</p>
  
  <p>I'm struggling to figure out a way to make this work, as any calls to save or update_attributes inside the Model simply results in an infinite loop (for obvious reasons).</p>
  
  <p>Is there a way to utilize either before_save or to override save in such a way that I can first check if a record exists with attributes x and y and if so retrieve that record and perform the update, otherwise move forward with a standard ActiveRecord save?</p>
  
  <p>Here is my code as it currently stands inside the Activity model, which does not work due to the infinite loop issue:</p>
  
  <pre><code>def save
    a = UserActivity.find_or_initialize_by_user_id_and_activity_id(user_id: user_id,     activity_id: activity_id)
    a.update_attributes start_at: start_at, end_at: end_at.....
  end
  </code></pre>