1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

add ActiveRecord::Base.has_attribute?

`has_attribute?` method to check wether a given attribute has been defined.
This commit is contained in:
Yves Senn 2015-12-02 16:57:29 +01:00
parent 0f82f661b7
commit 4294a7eebf
3 changed files with 27 additions and 2 deletions

View file

@ -191,6 +191,18 @@ module ActiveRecord
end
end
# Returns true if the given attribute exists, otherwise false.
#
# class Person < ActiveRecord::Base
# end
#
# Person.has_attribute?('name') # => true
# Person.has_attribute?(:age) # => true
# Person.has_attribute?(:nothing) # => false
def has_attribute?(attr_name)
attribute_types.key?(attr_name.to_s)
end
# Returns the column object for the named attribute.
# Returns a +ActiveRecord::ConnectionAdapters::NullColumn+ if the
# named attribute does not exist.

View file

@ -51,7 +51,7 @@ module ActiveRecord
end
attrs = args.first
if attribute_names.include?(inheritance_column)
if has_attribute?(inheritance_column)
subclass = subclass_from_attributes(attrs) || subclass_from_defaults
end
@ -163,7 +163,7 @@ module ActiveRecord
end
def using_single_table_inheritance?(record)
record[inheritance_column].present? && columns_hash.include?(inheritance_column)
record[inheritance_column].present? && has_attribute?(inheritance_column)
end
def find_sti_class(type_name)

View file

@ -1345,6 +1345,19 @@ class BasicsTest < ActiveRecord::TestCase
Company.attribute_names
end
def test_has_attribute
assert Company.has_attribute?('id')
assert Company.has_attribute?('type')
assert Company.has_attribute?('name')
assert_not Company.has_attribute?('lastname')
assert_not Company.has_attribute?('age')
end
def test_has_attribute_with_symbol
assert Company.has_attribute?(:id)
assert_not Company.has_attribute?(:age)
end
def test_attribute_names_on_table_not_exists
assert_equal [], NonExistentTable.attribute_names
end