trptcolin/consistency_fail — Issue #3: has_one associations are backed by unique indexes but consistency_fail still complains
Author: troessner
Created: 2012-01-04 19:17:29+00:00
State: open

It seems like consistency_fail is broken when it comes to has_one associations:

consistency_fail

There are calls to validates_uniqueness_of that aren't backed by unique indexes.
--------------------------------------------------------------------------------
Model Table Columns
--------------------------------------------------------------------------------
Prospect prospects (email)
--------------------------------------------------------------------------------

There are calls to has_one that aren't backed by unique indexes.
--------------------------------------------------------------------------------
Model Table Columns
--------------------------------------------------------------------------
Deal code_lists (deal_id)

Ok, let's fix that:

```Ruby
class AddUniqueIndices < ActiveRecord::Migration
def up
add_index :prospects, :email, :unique => true
add_index :code_lists, :deal_id, :unique => true
end

def down
remove_index :prospects, :email
remove_index :code_lists, :deal_id
end
end
```

Migrate:

bundle exec rake db:migrate
== AddUniqueIndices: migrating ===============================================
-- add_index(:prospects, :email, {:unique=>true})
-> 0.0326s
-- add_index(:code_lists, :deal_id, {:unique=>true})
-> 0.0301s
== AddUniqueIndices: migrated (0.0910s) ======================================

Now let's see what consistency_fails says:

consistency_fail

Hooray! All calls to validates_uniqueness_of are correctly backed by a unique index.

There are calls to has_one that aren't backed by unique indexes.
--------------------------------------------------------------------------------
Model Table Columns
--------------------------------------------------------------------------------
Deal code_lists (deal_id)

Ok, the validates_uniqueness_of issue is gone but the has_one is still there?

But the unique index IS there (output truncated):

rails c
Loading development environment (Rails 3.1.3)
>> CodeList.count
=> 66
>> CodeList.first.deal.id
=> 1
>> CodeList.last.deal.id
=> 66
>> CodeList.last.update_attribute :deal_id, 1
CodeList Load (0.5ms) SELECT `code_lists`.* FROM `code_lists` ORDER BY `code_lists`.`id` DESC LIMIT 1
(0.2ms) BEGIN
(0.9ms) UPDATE `code_lists` SET `deal_id` = 1, `updated_at` = '2012-01-04 19:14:46' WHERE `code_lists`.`id` = 132
(5.6ms) ROLLBACK
ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry '1' for key 'index_code_lists_on_deal_id': UPDATE `code_lists` SET `deal_id` = 1, `updated_at` = '2012-01-04 19:14:46' WHERE `code_lists`.`id` = 132

Seems to me like a bug or am I missing something here?