Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

AssociationScope#add_constraints, habtm, wrong primary_key

#6781

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.

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

State: new
Milestone: none
Assigned to: nobody
Importance: none

Activity

No comments yet.