Skip to content

Commit

Permalink
Add ActiveRecord::attribute_names to retrieve a list of attribute nam…
Browse files Browse the repository at this point in the history
…es. This method will also return an empty array on an abstract class or a model that the table doesn't exists.
  • Loading branch information
sikachu committed May 15, 2011
1 parent dde82a4 commit 5ca67ec
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
2 changes: 2 additions & 0 deletions activerecord/CHANGELOG
@@ -1,5 +1,7 @@
*Rails 3.1.0 (unreleased)*

* Add ActiveRecord::Base.attribute_names to return a list of attribute names. This will return an empty array if the model is abstract or table does not exists. [Prem Sichanugrist]

* CSV Fixtures are deprecated and support will be removed in Rails 3.2.0

* AR#new, AR#create, AR#create!, AR#update_attributes and AR#update_attributes! all accept a second hash as option that allows you
Expand Down
8 changes: 8 additions & 0 deletions activerecord/lib/active_record/base.rb
Expand Up @@ -767,6 +767,14 @@ def attribute_method?(attribute)
super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, '')))
end

def attribute_names
@attribute_names ||= if !abstract_class? && table_exists?
column_names
else
[]
end
end

# Set the lookup ancestors for ActiveModel.
def lookup_ancestors #:nodoc:
klass = self
Expand Down
13 changes: 13 additions & 0 deletions activerecord/test/cases/base_test.rb
Expand Up @@ -1790,4 +1790,17 @@ def test_marshal_round_trip

assert_equal expected.attributes, actual.attributes
end

def test_attribute_names
assert_equal ["id", "type", "ruby_type", "firm_id", "firm_name", "name", "client_of", "rating", "account_id"],
Company.attribute_names
end

def test_attribute_names_on_table_not_exists
assert_equal [], NonExistentTable.attribute_names
end

def test_attribtue_names_on_abstract_class
assert_equal [], AbstractCompany.attribute_names
end
end

0 comments on commit 5ca67ec

Please sign in to comment.