mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Use inheritance to avoid special-case code for the 'id' method
This commit is contained in:
parent
4c33d517d9
commit
61489dc684
4 changed files with 21 additions and 9 deletions
|
@ -9,7 +9,27 @@ module ActiveRecord
|
|||
[key] if key
|
||||
end
|
||||
|
||||
# Returns the primary key value
|
||||
def id
|
||||
read_attribute(self.class.primary_key)
|
||||
end
|
||||
alias _id id
|
||||
|
||||
# Sets the primary key value
|
||||
def id=(value)
|
||||
write_attribute(self.class.primary_key, value)
|
||||
end
|
||||
|
||||
# Queries the primary key value
|
||||
def id?
|
||||
query_attribute(self.class.primary_key)
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
def dangerous_attribute_method?(method_name)
|
||||
super && !['id', 'id=', 'id?', '_id'].include?(method_name)
|
||||
end
|
||||
|
||||
# Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the
|
||||
# primary_key_prefix_type setting, though.
|
||||
def primary_key
|
||||
|
|
|
@ -39,10 +39,6 @@ module ActiveRecord
|
|||
else
|
||||
define_read_method(attr_name, attr_name, columns_hash[attr_name])
|
||||
end
|
||||
|
||||
if attr_name == primary_key && attr_name != "id"
|
||||
define_read_method('id', attr_name, columns_hash[attr_name])
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
|
|
@ -17,10 +17,6 @@ module ActiveRecord
|
|||
write_attribute(attr_name, new_value)
|
||||
end
|
||||
end
|
||||
|
||||
if attr_name == primary_key && attr_name != "id"
|
||||
generated_attribute_methods.module_eval("alias :id= :'#{primary_key}='")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
@ -675,7 +675,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
|
|||
topic = Topic.new(:id => 5)
|
||||
topic.id = 5
|
||||
|
||||
topic.method(:id).owner.send(:remove_method, :id)
|
||||
topic.method(:id).owner.send(:undef_method, :id)
|
||||
|
||||
assert_deprecated do
|
||||
assert_equal 5, topic.id
|
||||
|
|
Loading…
Reference in a new issue