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

Ticket #5380 (new defect)

Opened 2 years ago

Last modified 2 years ago

Validations fail if an AR attribute has the same name as an existing [private] method

Reported by: chris@seagul.co.uk Assigned to: David
Priority: normal Milestone:
Component: ActiveRecord Version: 1.0.0
Severity: normal Keywords:
Cc:

Description

Validations will fail if an AR model has an attribute (column) with the same name as a previously defined method (anywhere in the inheritance chain); and, if the attribute has not already been accessed.

The attached patch adds a test to illustrate the problem.

The problem is that AR uses respond_to? to check whether a validation should send(:attr) or use [:attr]. respond_to? is overridden to always return true for an attribute. send(:attr) is then used to invoke the method. If the attribute has already been accessed then we will hit the method correctly. Similarly, if the method hasn't been accessed and no other method exists with the same name, the method gets created by method_missing. If, however, we haven't accessed the attribute and another method exists with the same name, we will invoke that.

The test in the patch creates a private method on Object that requires one argument. This makes the failure more obvious (as you get a 'wrong number of arguments' error), although you'll still see a failure when removing that required argument.

I started to think about patching the code to fix the problem but started getting stuck as to the best approach. My initial thoughts were based around creating a send_public method that would replicate send but obey visibility. This was because my problem was caused by a private method on Object. Having written this description I'm pretty certain the same problem will be observed with public methods too.

Attachments

validations_test.patch (0.8 kB) - added by chris@seagul.co.uk on 06/13/06 18:13:39.

Change History

06/13/06 18:13:39 changed by chris@seagul.co.uk

  • attachment validations_test.patch added.

06/13/06 18:15:18 changed by chris@seagul.co.uk

  • version set to 1.0.0.

I should point out that the patch is a failing test.

07/05/06 02:32:00 changed by david

  • summary changed from [PATCH] Validations fail if an AR attribute has the same name as an existing [private] method to Validations fail if an AR attribute has the same name as an existing [private] method.

Thanks for the test, but [PATCH] is only for ready-to-apply patches. Do add [PATCH] if you come up with a way to make the test pass.