title: Rails 4 encrypt foreign key
body: <p>I'm building an app that requires HIPAA compliance, which, to cut to the chase, means that I can't allow for certain connections to be freely viewable in the database (patients and recommendations for them).</p>
  
  <p>These tables are connected through the <code>patients_recommendations</code> table in my app, which worked well until I added the encryption via <a href="https://github.com/attr-encrypted/attr_encrypted" rel="nofollow">attr_encrypted</a>. In an effort to cut down on the amount of encrypting and decrypting (and associated overhead), I'd like to be able to simply encrypt the <code>patient_id</code> in the <code>patients_recommendations</code> table. However, upon changing the data type to <code>string</code> and the column name to <code>encrypted_patient_id</code>, the app breaks with the following error when I try to reseed my database:</p>
  
  <blockquote>
    <p>can't write unknown attribute `patient_id'</p>
  </blockquote>
  
  <p>I assume this is because the join is looking for the column directly and not by going through the model (makes sense, using the model is probably slower). Is there any way that I can make Rails go through the model (where <code>attr_encrypted</code> has added the necessary helper methods)?</p>
  
  <p><strong>Update:</strong></p>
  
  <p>In an effort to find a work-around, I've tried adding a before_save to the model like so:</p>
  
  <pre><code>before_save :encrypt_patient_id
  
  ...
  
  private
  
  def encrypt_patient_id
    self.encrypted_patient_id = PatientRecommendation.encrypt(:patient_id, self.patient_id)
    self.patient_id = nil
  end
  </code></pre>
  
  <p>This doesn't work either, however, resulting in the same error of <code>unknown attribute</code>. Either solution would work for me (though the first would address the primary problem), any ideas why the <code>before_save</code> isn't being called when created through an association?</p>