title: How to guarantee MySQL lock acquisition order in Rails
body: <p>We are using Rails 4.1 and we a model with a has_many.</p>
  
  <p>Model X has_many Y </p>
  
  <p>Y can be updated and will then update X through callbacks (increment a version field, modified_at, etc)</p>
  
  <p>X can also be updated by itself.</p>
  
  <p>This is causing deadlocks inside MySQL since one transaction will locked Y1 then want to lock X1 while another transaction will have locked X1 then want to lock Y1.</p>
  
  <p>This is easy to fix by requiring at a minimum a <code>SELECT ... FOR UPDATE</code> on the owning X before updating a Y.</p>
  
  <p>How do I do this in Rails? Or is there an even better solution?</p>
  
  <p>I am considering trying to guarantee that I have a transaction in a before_update callback on Y and then acquiring a lock on X but I am not sure that will work well with Rails.</p>