This project is archived and is in readonly mode.

#6781 new
Marian Rudzynski

AssociationScope#add_constraints, habtm, wrong primary_key

Reported by Marian Rudzynski | May 14th, 2011 @ 06:30 PM

Take these two classes:

class User < ActiveRecord::Base
  set_primary_key :wtf_id
  has_and_belongs_to_many :badges, :join_table => "user_badges"
class Badge < ActiveRecord::Base
  has_and_belongs_to_many :users, :join_table => "user_badges"

user_badges looks typical:

    create_table :user_badges, :id => false do |t|
       t.integer :user_id
       t.integer :badge_id

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.

No comments found

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href=""></a>

People watching this ticket