rails/rails — pull request #3748 by samsonasu (2011-11-24 20:53:07+00:00)
Title: New records should load has_many relationships with custom primary keys

If a has_many relationship is defined with a custom primary key, a new, unsaved record with that key set will not load the association. This is because AR checks new_record? and assumes (correctly in normal situations) that an unsaved record couldn't possibly have any related records, so it skips the round trip to the database.

I believe this is an error, and the association should be loaded from the database.

```ruby
class Author < ActiveRecord::Base
has_many :essays, :primary_key => :name, :as => :writer
end

Author.new(:name => "David").essays # => []
# => Should return [#]
```

This pull request fixes this issue. I tested the 4 big connection adapters and added 2 tests.

I overrode the foreign_key_defined? method in has_many_association to handle this since that seemed to be written almost specifically for this purpose in has_many_through, but if that isn't the best way to handle this I'm open to discussion.

Thanks