Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #9758 (new defect)

Opened 8 months ago

Last modified 6 months ago

[PATCH] Reflections return incorrect class_name for nested AR models

Reported by: mindforge Assigned to: core
Priority: normal Milestone: 2.x
Component: ActiveRecord Version: edge
Severity: normal Keywords: unverified
Cc:

Description

Reflections generate the default class_name for the associated object(s) from the association-name. This fails, however, when two models are in the same module and the association does not get the class_name set explicitly.

This results in a bug, when the :dependent flag is set to :delete_all (and presumably also for :destroy and :nullify). The generated before_destroy callbacks (in associations.rb, starting at line 1131) use reflection.class_name, which then cannot be found and results in an exception.

Some example code:

module AccessControl
  class Account < ActiveRecord::Base
    has_many :roles, :dependent => :delete_all
    [...snip...]
  end
  
  class Role < ActiveRecord::Base
    belongs_to :account
    [...snip...]
  end
end

account = AccessControl::Account.create!
account.roles.create!
account.destroy

The has_many association would generate the following callback code:

before_destroy { |record| Role.delete_all(%([...snip...])) }

Instead, it should be:

before_destroy { |record| AccessControl::Role.delete_all(%([...snip...])) }

I have attached a patch for this bug and added two test-cases, which pass the reflection tests using MySQL. Since this is not adapter-specific code, I do not expect problems on other databases.

Attachments

active_record_reflection_fix.patch (1.7 kB) - added by mindforge on 10/10/07 11:39:14.

Change History

10/10/07 11:39:14 changed by mindforge

  • attachment active_record_reflection_fix.patch added.

10/10/07 11:45:33 changed by mindforge

I made the incorrect assumption, that MacroReflection#active_record holds an AR object rather than an AR class. So I tested for the wrong thing and had the code satisfy the incorrect tests.

I just uploaded a corrected patch, that fixes this mistake.

11/10/07 08:01:07 changed by mindforge

  • keywords changed from reflection dependent to unverified.