Take these two classes:
class User < ActiveRecord::Base
set_primary_key :wtf_id
has_and_belongs_to_many :badges, :join_table => "user_badges"
end
class Badge < ActiveRecord::Base
has_and_belongs_to_many :users, :join_table => "user_badges"
end
user_badges looks typical:
create_table :user_badges, :id => false do |t|
t.integer :user_id
t.integer :badge_id
end
user.badges will generate the following SQL:
SELECT "badges".* FROM "badges" INNER JOIN "user_badges" ON "badges"."wtf_id" = "user_badges"."badge_id" WHERE "user_badges"."user_id" = 1
That is because in AssociationScope#add_constraints
(lib/active_record/associations/association_scope.rb:59,
source_macro = :habtm) table ends up being 'badges' while
reflection.active_record is the User class.
The fix is straight-forward:
at lib/active_record/associations/association_scope.rb:59 use
table[reflection.klass.primary_key] instead of
table[reflection.active_record_primary_key]
However, I haven't traced any further and I'm not exactly fluent
in the internals, so the real solution might be somewhere else.
That is why I haven't sent a pull request or attached a diff.