title: How to avoid UniqueViolation errors
body: <p>My facebook-like application gives users the opportunity to delete unwanted messages from following users. For this purpose I created a <code>MicropostQuarantine</code> association between users and microposts: if such an association between a user and a micropost exists, then that user will not see that micropost in their feed. However, microposts will be visible also in a user's profile page, included those already in quarantine. So, if I removed a micropost from my feed and visited the profile page of that micropost's user, I would still see that micropost and have access to the remove button that would raise the following error:</p>
  
  <pre><code>ActiveRecord::RecordNotUnique (PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "index_micropost_quarantines_on_user_id_and_micropost_id"
  DETAIL:  Key (user_id, micropost_id)=(1, 300) already exists.
  : INSERT INTO "micropost_quarantines" ("user_id", "micropost_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"):
  </code></pre>
  
  <p>The quarantine method in the microposts controller is simple:</p>
  
  <pre><code>def quarantine
    current_user.micropost_quarantines.create!(micropost_id: @micropost.id)
  end
  </code></pre>
  
  <p>There is a <code>before_action :entitled_user, only: :quarantine</code> defined as follows:</p>
  
  <pre><code>def entitled_user
    @micropost = Micropost.find(params[:id])
    redirect_to root_url unless (current_user == @micropost.user || current_user.following.include?(@micropost.user))
  end
  </code></pre>
  
  <p>As you can see a user can only quarantine his own microposts and microposts from following users. In order to avoid UniqueViolation errors, I thought of adding some code to the <code>entitled_user</code> method, to check if the association already exists:</p>
  
  <pre><code>def entitled_user
    @micropost = Micropost.find(params[:id])
    @quarantine = MicropostQuarantine.find_by(micropost_id: @micropost.id, user_id: current_user.id)
    redirect_to root_url unless (current_user == @micropost.user || current_user.following.include?(@micropost.user) || @quarantine.nil?)
  end    
  </code></pre>
  
  <p>However this does not work: the <code>entitled_user</code> method is ignored/bypassed by rails for some unknown reasons, I keep receiving the <code>UniqueViolation: ERROR</code> from ActiveRecord and the whole <code>unless</code> conditional is ignored, so that I would be able to quarantine microposts from non following users.</p>