Skip to content
This repository
Browse code

Use inheritance to avoid special-case code for the 'id' method

  • Loading branch information...
commit 61489dc6844539c86558f00670802c71927f9b51 1 parent 4c33d51
Jon Leighton jonleighton authored
20 activerecord/lib/active_record/attribute_methods/primary_key.rb
@@ -9,7 +9,27 @@ def to_key
9 9 [key] if key
10 10 end
11 11
  12 + # Returns the primary key value
  13 + def id
  14 + read_attribute(self.class.primary_key)
  15 + end
  16 + alias _id id
  17 +
  18 + # Sets the primary key value
  19 + def id=(value)
  20 + write_attribute(self.class.primary_key, value)
  21 + end
  22 +
  23 + # Queries the primary key value
  24 + def id?
  25 + query_attribute(self.class.primary_key)
  26 + end
  27 +
12 28 module ClassMethods
  29 + def dangerous_attribute_method?(method_name)
  30 + super && !['id', 'id=', 'id?', '_id'].include?(method_name)
  31 + end
  32 +
13 33 # Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the
14 34 # primary_key_prefix_type setting, though.
15 35 def primary_key
4 activerecord/lib/active_record/attribute_methods/read.rb
@@ -39,10 +39,6 @@ def define_method_attribute(attr_name)
39 39 else
40 40 define_read_method(attr_name, attr_name, columns_hash[attr_name])
41 41 end
42   -
43   - if attr_name == primary_key && attr_name != "id"
44   - define_read_method('id', attr_name, columns_hash[attr_name])
45   - end
46 42 end
47 43
48 44 private
4 activerecord/lib/active_record/attribute_methods/write.rb
@@ -17,10 +17,6 @@ def define_method_attribute=(attr_name)
17 17 write_attribute(attr_name, new_value)
18 18 end
19 19 end
20   -
21   - if attr_name == primary_key && attr_name != "id"
22   - generated_attribute_methods.module_eval("alias :id= :'#{primary_key}='")
23   - end
24 20 end
25 21 end
26 22
2  activerecord/test/cases/attribute_methods_test.rb
@@ -675,7 +675,7 @@ def test_dispatching_column_attributes_through_method_missing_deprecated
675 675 topic = Topic.new(:id => 5)
676 676 topic.id = 5
677 677
678   - topic.method(:id).owner.send(:remove_method, :id)
  678 + topic.method(:id).owner.send(:undef_method, :id)
679 679
680 680 assert_deprecated do
681 681 assert_equal 5, topic.id

0 comments on commit 61489dc

Please sign in to comment.
Something went wrong with that request. Please try again.