title: why PG::UniqueViolation: ERROR: duplicate key value violates unique constraint?
body: <p>I have a model <code>Post</code> and each time a post is created I want a new instance of <code>Moderation</code> to be created at the same time.</p>
  
  <p>So in post.rb I use the callback <code>after_save :create_moderation</code>
  Then write a private method :</p>
  
  <pre><code> ...
   include Reportable
   after_save :create_moderation
  
   private
   def create_moderation
      self.create_moderation!(blog: Blog.first)
   end
  </code></pre>
  
  <p>But when a proposal is created I get this error :</p>
  
  <blockquote>
    <blockquote>
      <p>PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "moderations_reportable" DETAIL: Key (reportable_type, reportable_id)=(Post, 25) already exists. : INSERT INTO "moderations" ("blog_id", "reportable_type", "reportable_id", "created_at", "updated_at", "blog_type") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"</p>
    </blockquote>
  </blockquote>
  
  <p>In reportable.rb I have :</p>
  
  <pre><code>  has_one :moderation, as: :reportable, foreign_key: "reportable_id", foreign_type: "reportable_type", class_name: "Moderation"
  </code></pre>
  
  <p>Then few other methods for reportable object.</p>
  
  <p>Note that this issue doesn't happen when I run the create method in console.</p>
  
  <p><strong>EDIT</strong></p>
  
  <pre><code>  create_table "moderations", id: :serial, force: :cascade do |t|
      t.string "reportable_type", null: false
      t.string "reportable_id", null: false
      t.integer "blog_id", null: false
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
      t.string "blog_type", null: false
      t.string "upstream_moderation", default: "unmoderate"
      t.index ["blog_id", "blog_type"], name: "moderations_blog"
      t.index ["reportable_type", "reportable_id"], name: "moderations_reportable", unique: true
    end
  
  
  
  create_table "posts", id: :serial, force: :cascade do |t|
      t.text "title", null: false
      t.text "body", null: false
      t.integer "feature_id", null: false
      t.integer "author_id"
      t.integer "scope_id"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
      t.integer "post_votes_count", default: 0, null: false
      t.index ["body"], name: "post_body_search"
      t.index ["created_at"], name: "index_posts_on_created_at"
      t.index ["author_id"], name: "index_posts_on_author_id"
      t.index ["feature_id"], name: "index_posts_on_feature_id"
      t.index ["proposal_votes_count"], name: "index_posts_on_post_votes_count"
      t.index ["title"], name: "post_title_search"
    end
  </code></pre>