rails/rails — Issue #3987: ActiveRecord >=3.1 / setting primary_key to an column defined in the db as auto-increment but not primary key
Author: kjg
Created: 2011-12-14 19:20:36+00:00
State: open

When using a legacy database or when writing to a view, if a column is set to auto-increment, but the schema doesn't define it as a "primary key", then active record fails to properly set the primary_key column in the schema_cache early enough.

It looks like by calling #create, the schema_cache's colums are filled before AR:Base#columns gets called. #columns being the method that sets the primary_key in the cache

I've included a failing test as well as a proposed fix in [this gist](https://gist.github.com/1410534).

In my opinion #columns is probably not the place to be putting the primary_key in the cache though since clearly the column definitions in the cache are filled before #columns is called. A better fix would be to either 1. find a better time earlier in the query life cycle to cache the primary_key as set by AR, or 2. cache the column definitions later in the query cycle.