From 4294a7eebf52759be61ed57908436d6324f26120 Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Wed, 2 Dec 2015 16:57:29 +0100 Subject: add `ActiveRecord::Base.has_attribute?` `has_attribute?` method to check wether a given attribute has been defined. --- activerecord/lib/active_record/attribute_methods.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'activerecord/lib/active_record/attribute_methods.rb') diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index 4ae585d3f5..423a93964e 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -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. -- cgit v1.2.3